对字符串匹配数组的话 [英] Match array words against string

查看:188
本文介绍了对字符串匹配数组的话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经重新格式化了这个问题,因为一个误会,这产生敌意对我和问题,并不是有意而为它我appologise。

I have reformatted this question, due to a misunderstanding, which generated ill feeling toward me and the question, not intentionally and for it I appologise.

我有我使用突出在一个字符串的单词的排列,有些话却可能显示为一个短语的一部分,所以我想这句话采取presidence的亮点:

I have an array of words which I am using to highlight words in a string, some of the words however might appear as part of a phrase, and so I would like the phrase to take presidence in the highlight:

例如:

// Array
   $seo = array("apple, apple tree, orchard");

// String 
   $description = "In my orchard I have a large Apple Tree";

// Desired effect: 
   In my <strong>orchard</strong> I have a large <strong>Apple Tree</strong>

在我自己的第一次尝试,我通过数组循环运行针对字符串preg_replace,但我正在逐渐嵌套的亮点像这样&LT;强&GT;&LT;强&GT;苹果&LT; / STRONG&GT ;树&LT; / STRONG&GT;

In my own first attempt, I looped through the array running a preg_replace against the string, but I am getting nested highlights like this <strong><strong>Apple</strong> Tree</strong>

提前感谢您的帮助。

斯图

推荐答案

首先,你不应该使用一个循环来代替每个单独的词,而是一个正则表达式的选择列表(富|酒吧|啄)

First, you shouldn't use a loop to replace each word individually, but a regex alternatives list (foo|bar|thingy).

  $rx_words = implode("|", array_map("preg_quote", $words));
  $text = preg_replace("/\b($rx_words)\b/i", 

(其实这preg_quote错过了第二个参数,但只要你没有期待中的关键字斜线,它会工作。)

(Actually that preg_quote misses the second param, but as long as you don't have forward slashes in the keywords, it'll work.)

那么你也可以让它具有更安全的断言:

Then you can also make it safer with an assertion:

  $text = preg_replace("/(?<!<strong>)\b($rx_words)\b/i",

所以会忽略那些已经包裹的话。这只是一个解决办法,但往往就足够了。

So it will ignore words that are already wrapped. That's just a workaround, but quite often sufficient.

这篇关于对字符串匹配数组的话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆