dongpo3957 2012-05-16 08:25 采纳率: 0%
浏览 40
已采纳

不区分大小写的子串首先在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?

  • 写回答

4条回答 默认 最新

  • dongwei4444 2012-05-16 08:28
    关注

    + 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题