【问题标题】:preg_replace <strong>apple <strong>tree</strong></strong>preg_replace <strong>苹果<strong>树</strong></strong>
【发布时间】:2011-12-28 12:20:49
【问题描述】:

所以问题..我已经坚持这个一个月了,所以请任何帮助将不胜感激。

我正在尝试从数组中的单词中突出显示字符串中的单词。我遇到的问题是嵌套标签。

$bold=array();
$bold="tree,apple tree,orange";
$description="orange and apple tree";

例如; the result I want would be this &lt;strong&gt;orange&lt;/strong&gt; and &lt;strong&gt;apple tree&lt;/strong&gt;, but the result I am getting is this &lt;strong&gt;orange&lt;/strong&gt; and &lt;strong&gt;apple &lt;strong&gt;tree&lt;/strong&gt;&lt;/strong&gt;

我已经拼凑了这个,但它不能按预期工作,所以如果我的方法不正确,请随时修改或丢弃。

function highlightWords($text, $words){
 foreach ($words as $word){
  $word = preg_quote($word);
  $word = (str_replace("/","",$word));
  $text = preg_replace("/(?!<.*?)(".preg_quote($word,'/').")(?![^<>]*?>)/si",'<strong>\1</strong>', $text);
 }
 return $text;
}
$description =  highlightWords($description, $bold);

【问题讨论】:

  • 你给出的输出有什么问题?
  • 我想要 apple tree 而不是 apple tree

标签: php preg-replace


【解决方案1】:

如果我正确理解了您的问题,这就是您的解决方案:

function highlightWords($text, array $words){
  $words = array_map(preg_quote, $words);
  return preg_replace('/(' . implode('|', $words). ')/is', '<strong>$1</strong>', $text);
}

$text = 'orange and aPPle tree';
$boldWords = array('tree', 'apple tree', 'orange');

$text =  highlightWords($text, $boldWords);
echo $text;

示例:http://www.ideone.com/at4lw

您使用初始文本和要突出显示的单词数组调用函数 highlightWords。该函数返回带有突出显示的单词的文本。

【讨论】:

  • 如果你不想尊重大写,只需使用函数str_ireplace而不是str_replace
  • 您完美地预料到了我的下一个问题......并且您的代码可以正常工作,但替换了案例。我可以保持原样吗?
  • 回到我现在的位置,使用嵌套的 标签。 grrrrr,这太令人沮丧了。有什么想法吗?
  • 最后一次尝试 :) 再次更新。
  • 美丽!!!!!!!!!阿明,非常感谢你,这真的让我很头疼!!不太确定我是否理解内爆('|',但我可以进一步调查,以便我学会理解。
【解决方案2】:

很好的答案。就个人而言,我还提到您应该(或可以)修改它以仅查找整个单词。例如,如果您的 $boldWords 包含“ad”,并且如果您的文本包含“lead”和“had”,那么您最终会遇到一些奇怪的问题。

使用 \b 添加单词“boundaries”以仅匹配整个单词。

return preg_replace('/\b(' . implode('|', $words). ')\b/is', '<strong>$1</strong>', $text);

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 2011-01-13
    • 2011-03-23
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多