PHP 中不区分大小写的子字符串首次出现替换


Case insensitive sub-string first appearance replacement in PHP

我想执行不区分大小写的子字符串首次出现替换。

我试过这段代码:

$product_name_no_manufacturer = preg_replace("/$product_manufacturer/i","",$product_name, 1);
$product_name_no_manufacturer = trim($product_name_no_manufacturer);

但在某些情况下它不起作用。

什么时候-

$product_name = "3M 3M LAMP 027";
$product_manufacturer = "3m";

我得到的结果是:

"3M灯027"

但是当参数不同时——

$product_name = "A+k A+k-SP-LAMP-027";
$product_manufacturer = "A+k";

我得到的结果是:

"A+k A+k-SP-LAMP-027"

为什么preg_replace不能取代A+k的第一次出现?

+是正则表达式中的一个特殊字符("匹配前面的标记一次或多次"),因此您必须对其进行转义。每当您将字符串插入正则表达式时,请使用 preg_quote() 对其进行转义,因为它可能包含特殊字符(在这种情况下会导致看似奇怪的结果)。

$quoted = preg_quote($product_manufacturer, '/');
$product_name_no_manufacturer = preg_replace("/$quoted/i", "", $product_name, 1);

preg_quote()就是你要找的。

虽然

. ' + * ? [ ^ ] $ ( ) { } = ! < > | : -

是模式中的特殊字符,您必须先转义它们(A+k 变为 A''+k)。

编辑:此处的示例。

则表达式中的+有特殊的手段,你应该转义它。

实际上,这可以在没有任何正则表达式的情况下解决。有一个有用的函数 strtr。因此,您可以像这样使用它:

$product_name_no_manufacturer 
         = strtr( $product_manufacturer, array( $product_name => '' ) );

这将比正则表达式更快,我认为更方便。