从字符串中替换一些单词

时间:2015-03-07 19:48:07

标签: php regex string preg-replace

我想从字符串中删除一些单词:

  1. 这个词: fa
  2. 这个词: livicon
  3. 所有以 fa - 开头的单词(在这种情况下为fa-word和fa-word-small,但这些单词也可以不同。例如fa-user)
  4. 字符串:

    fa fa-word livicon fa-word-small fantastic
    

    输出

    fantastic
    

1 个答案:

答案 0 :(得分:0)

您希望将preg_replace()与使用word boundaries的正则表达式以及前缀字符串的-word-etc部分的可选分组结合使用。以下就足够......

$str = 'fa fa-word livicon fa-word-small fantastic';
$str = preg_replace('~\b(?:fa(?:-\w+)*|livicon)\b~', '', $str);
echo trim($str); //=> "fantastic"
相关问题