不区分大小写的子串首先在PHP中替换外观

I want to perform a case insensitive sub-string first appearance replacement.

I've tried this code :

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

but it doesn't work in some cases.

When -

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

$product_manufacturer = "3m";

the result I get is :

"3M LAMP 027"

But when the parameters are different -

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

$product_manufacturer = "A+k";

the result I get is :

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

Why preg_replace doesn't replace the first appearance of A+k?

+ is a special character in Regex ("match the preceding token once or more"), so you have to escape it. Whenever you insert a string into your Regex, escape it with preg_quote(), because it can contain special characters (leading to seemingly strange results as in this case).

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

preg_quote() is what you are looking for.

Though

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

are special characters in a pattern, you have to escape them first (A+k becomes A\+k).

Edit: Example here.

+ in regex have special means, you should escape it.

Actually, this can be solved without any regular expressions. There is a useful function strtr. So, you can use it like that:

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

This will be more faster than regexp and I think more convenient.