PHP正则表达式替换中的可选字符

4

我从数据库中获取了这种格式的数据...

BUS 101S Business and Society

或者

BUS 101 Business and Society

注意可选的“S”字符(可以是任何大写字符)
我需要用空值替换“BUS 101S”部分,以下是我的解决方案...
$value = "BUS 101S Business and Society";
$sub = substr($value, 0, 3); // Gives me "BUS"
$num = substr($value, 4, 3); // Gives me "101"
$new_value = preg_replace("/$sub $num"."[A-Z]?/", null, $value);

$new_value的值现在包含S Business and Society。所以我已经接近了,只需要将可选的大写字母替换掉。有什么想法吗?


你的代码已经可以正常工作了,但是有更简单的方法来实现它! - Cal
嗯... 这很奇怪。我同意有更简单的方法,哈哈,很高兴从答案中看到了这一点。 - Alex_Hyzer_Kenoyer
3个回答

10

假设模式为3个大写字母,3个数字,然后是可选的大写字母,只需使用单个preg_match函数:

$new = preg_replace('/^[A-Z]{3} \d{3}[A-Z]?/', '', $old);

^ 只会匹配行/字符串的开头。 {3} 表示“前面的模式正好匹配3次”。? 表示“前面的模式匹配0或1次”。


好的,我已经在一个新的PHP文件中尝试了您的代码,并且结合我在问题中发布的内容,它运行得非常好,因此这就是我的问题的答案。然而,它为什么不能在我的其他代码中工作,这让我很抓狂,但肯定还有其他问题,不同于我在问题中所提到的。感谢您的帮助。 - Alex_Hyzer_Kenoyer

1
你还可以像这样做,这样就不用麻烦地使用 substr 了。
preg_replace('#^[A-Z]{3} [0-9]{3}[A-Z]? (.*)$#', '$1', $value);

或者使用 preg_match,获取字符串的所有组件

if (preg_match('#^([A-Z]{3}) ([0-9]{3})([A-Z]?) (.*)$#', $value, $matches)) {
    $firstMatch=$matches[1];//BUS ($matches[0] is the whole string)
    $secondMatch=$matches[2];//101
    $secondMatch=$matches[3];//S or ''
    $secondMatch=$matches[4];//the rest of the text
}

我同意,尽管我需要使用 substr() 因为我稍后会用到这些变量,但感谢您指出了简化正则表达式阅读的方法。 - Alex_Hyzer_Kenoyer
然后您可以使用 preg_match,查看我的更新答案(几分钟内)。 - haltabush
我不知道那个。谢谢你指出来!但愿我能接受两个答案... - Alex_Hyzer_Kenoyer

0

这样做不是更简单吗:

$str = 'BUS 101S Business and Society';
$words = explode(' ', $str);
array_unshift($words); // bus
array_unshift($words); // 101s
$str = implode(' ', $words);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接