0

PHPを使用してhtmlデータを配列値に置き換える必要があるプロジェクトに取り組んでいますpreg_replace()

コードを見てください

コード

 $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更新されません。

4

1 に答える 1

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

する必要があります:

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

変数は、一重引用符ではなく、二重引用符内でのみ置換されます。

preg_replaceすべてのテキストが通常の文字列であるのに、なぜ使用しているのですか?どうしてstr_replace

1回の呼び出しですべての置換を行うこともできます。str_replaceは、検索文字列と置換文字列の配列を受け取ることができます。

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

または正規表現を使用すると、パイプを使用してすべての単語を一致させることができます。

$ regex = implode('|'、$ texts); preg_replace( "/ $ regex /"、'$ 0'、$ sample);

于 2012-10-02T09:11:54.097 に答える