2013-03-19 52 views
0

我有一个内容描述和少数列出的词(“谷歌”和“Gmail”)。现在,如果这些词出现在内容描述中,那么我必须用它们的链接来替换它们。我创建了一个正则表达式,并使用preg_match成功替换了它们。但现在我想限制它们。例如: 如果发现2个词非常接近,它们将不会被替换。 我的介绍如下:限制字符串替换如果匹配发现非常接近preg_replace在PHP

“这是我对谷歌和Gmail说明我需要它的链接,同时也是Gmail来取代谷歌”

现在,我的要求是,首先Gmail中不应该被替换,因为第一“Google”非常接近它(仅有1个字距),其余的字应该被替换,因为它们彼此之间距离很远。所以我的结果应该是:

This is my description for <a href="google.com">Google</a> and Gmail. I need to replace <a href="google.com">Google</a> with its link and also <a href="gmail.com">Gmail</a>. 

我已经使用了前瞻性匹配,但它不起作用。

+0

你如何量化“非常接近”和“非常远”?您需要精确定义这些以确定您的解决方案。 – nickb 2013-03-19 14:52:57

+0

先替换所有'Googles-not-follow-by-Gmail',然后替换所有的Gmail。 ) – raina77ow 2013-03-19 14:53:45

+0

@nickb实际上,OP定义了它:“仅1个字距”。例如,Google在'Google和Gmail'的短语中与Gmail太靠近了。 – raina77ow 2013-03-19 14:54:18

回答

0

好的我得到了解决方案。

我使用preg_match_all为每个单词逐一,然后维护与偏移量(PREG_OFFSET_CAPTURE)的匹配单词数组。

现在我管理所有与位置匹配的单词列表,并根据单词的权重对列表进行排序。现在我们可以使用任何算法来追踪文本中最近的替换。我做了如下:

1: Replace first list word in body and maintain a temp tracking array with position of this word. 
2: For second word in list, first check the temp tracking array and find nearest position of second word. Now you can find words between first word and second word using str_word_count function. 
3: Now do this for all words in list.