替换字符串中的一些单词

replace some words from a string

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

  1. 单词:fa
  2. 单词:livicon
  3. 所有以fa-开头的词(在本例中是fa-word和fa-word-small,但这个词也可以不同。例如fa-user)

字符串:

fa fa-word livicon fa-word-small fantastic

输出应该是

fantastic

您想对前缀字符串的 -word-etc 部分使用 preg_replace() with a regular expression that uses word boundaries 和可选分组。以下就足够了...

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