2013-03-19 38 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.