【问题标题】:How can I replace words which are surrounded with special characters?如何替换用特殊字符包围的单词?
【发布时间】:2014-08-07 12:16:22
【问题描述】:

我想使用preg_replace()删除被特殊字符包围的单词:

$product_name =  'Choose a   : giFt ,';
$word = 'gift';
$regex = '/[-:,]?\b'.$word.'\b[-:,]?/i';
if(preg_match($regex, $product_name))
{
  $str = preg_replace($regex, "", trim($product_name));
}
echo $str;

输出:

Choose a  :  ,

如果我的字符串是“Choose a :giFt”,则如果没有空格就可以正常工作。

我的预期输出是

Choose a

【问题讨论】:

    标签: php regex string preg-replace


    【解决方案1】:

    你必须试试这个:

    $regex = '`:([^>]+),`';
    

    但是你也必须清理你的代码,你不需要 $regex 和 $regex_p

    【讨论】:

      【解决方案2】:

      只需在你的角色类中添加空格:

      $regex = '/[-:,\s]*\b'.$word.'\b[-:,\s]*/i';
      

      【讨论】:

        猜你喜欢
        • 2014-06-18
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 2021-09-20
        • 1970-01-01
        相关资源
        最近更新 更多