2015-06-16 42 views
0

我想匹配兩個字符串,如果有任何單詞匹配我想爲它們添加標記。在php中比較兩個字符串並添加標記

我試過類似下面下面的代碼

$old = "one two three"; 

$new = "how is one related to two"; 

foreach (explode(" ", $old) as $str) { 
    $str .= str_replace($str, "<b>$new</b>", $str); 
} 
echo trim($str); 

Exptected結果how is <b>one</b> related to <b>two</b>

如果可能的話,請給我建議一些其他的方式,如循環。如果不可能,請告訴我循環。

回答

2

記住:

str_replace(look_for_this , replace_it_wtih_this, look_through_this); 

在代碼中,你使用.=,這將只是複製在每個迭代上一個新的句子。我會做這種方式:

$old = "one two three"; 
$sentence = "how is one related to two"; 
$arr = explode(" ", $old); 
foreach ($arr as $word) { 
    $sentence = str_replace($word, "<b>$word</b>", $sentence); 
} 
echo trim($sentence); 

結果:

how is <b>one</b> related to <b>two</b> 
+0

嘿感謝!沒有循環可能嗎?我必須在單個頁面中檢查1000個句子....或僅循環是要走的路? – Vishnu

+0

要檢查的文本數量不是問題,循環只會通過向'$ old'添加更多單詞來獲得更多迭代。 –

+0

好.. +1 :)接受 – Vishnu

0

試試這個:

foreach(explode(" ",$old) as $lol) 
{ 
    $new = str_replace($lol, "<b>".$lol."</b>", $new); 
} 
1

這是一個辦法做到這一點,我認爲錯誤是使用.=代替=以及一些混合參數str_replace()PHP Sandbox

$searchwords = "one two three"; 

$string = "how is one related to two"; 

foreach (explode(" ", $searchwords) as $searchword) { 
    $string = str_replace($searchword, "<b>{$searchword}</b>", $string); 
} 

echo trim($string); 
+0

我接受已經兄弟..雖然;);) – Vishnu

0

嘗試使用preg_replace函數,而不是循環

<?php 
$pattern = "/one|two|three/i"; 
$string = "how is one related to two"; 
$replacement = "<b>$0</b>"; 
$result = preg_replace($pattern, $replacement, $string); 
echo $result; 

結果將是

how is <b>one</b> related to <b>two</b> 

您可以從here檢查出的preg_replace。

0

的preg_replace所有:

function _replace($old,$new){ 
    $search = str_replace(' ',')|(',$old); 
    return preg_replace("/($search)/i",'<b>$0</b>',$new); 
} 
echo _replace("one two three","how is one related to two");