2012-10-02 26 views
0

我們在一個項目中,我們有使用PHP preg_replace()用簡單的HTML DOM在Preg_replace中使用PHP替換數組值?

數組值請看代碼

代碼

$html = new simple_html_dom(); 
$texts = array('Replace','the', 'asterisks','prefer','it','all','functions','will','replace','computer','strategic','casio','computing','smart'); 
$html->load("<body><div>Replace the asterisks in a list with numbers in order</div><div>or if you prefer it all condensed down into a single smart</div><li>Both functions will replace placeholder</li><li>smart</li></body>"); 
$sample = &$html->outertext ; 
foreach($texts as $text){ 
    $fine = trim($text); 
    $replace = '<u>'.$fine.'<\u>'; 
    if(!empty($text)){ 
if (strpos($sample,$fine)){ 
$sample = preg_replace('/$fine/',$replace,$sample); 
$html->save(); /// Update all the replaces on $html ; 
} 
    } 
} 

echo $sample; 

打印取代HTML數據工作的同$html ,沒有更新。

回答

0
preg_replace('/$fine/',$replace,$sample); 

應該是:

preg_replace("/$fine/",$replace,$sample); 

變量僅取代的雙引號,不單引號內。

爲什麼你在使用preg_replace時,你的所有文本都是普通字符串?爲什麼不是str_replace

您也可以在一次調用中完成所有替換。 str_replace函數可以搜索和替換字符串數組:

$replacements = array_map(function($e) {return "<u>$e</u>";}, $texts); 
str_replace($texts, $replacements, $sample); 

或正則表達式,你可以使用管道以匹配所有的話:

$正則表達式=破滅(「|」,$文本); preg_replace(「/ $ regex /」,'$ 0',$ sample);

+0

普通字符串的意思是,值可以不同,它取決於用戶。所以請告訴我哪種方法最適合我們?謝謝 – Sam

+0

用戶是否允許給出像'a。* b'這樣的正則表達式來匹配以'a'開頭並以'b'結尾的任何東西?或者他們只是應該完全匹配的字符串? – Barmar

+0

我們只處理文字,如果我們匹配兩個網站,那麼重複的單詞將突出顯示。我們只是將這個腳本應用於。有沒有其他適合它的想法? – Sam