在php中使用替换匹配完整的单词

时间:2013-11-15 16:21:30

标签: php html css regex replace

我在PHP中使用替换函数来替换和下划线

  $replace='<span style="font-weight:bold; border-bottom: 1px solid #999999;" >'.$term.'</span>';
  $post = str_ireplace($term, $replace, $post,$count);

问题在于,如果匹配的字词是are且主题是care,那么它只是强调are而不是c,任何其他方式都可以这样做它应该强调整个词。

1 个答案:

答案 0 :(得分:4)

$replace='<span style="font-weight:bold; border-bottom: 1px solid #999999;" >$0</span>';
$post = preg_replace("/[a-z]*{$term}[a-z]*/i", $replace, $post);

[a-z]*匹配任何字母序列,因此这将包括匹配项中匹配术语周围的其余部分。 $1中的$replace将替换为与正则表达式匹配的任何内容。

DEMO