Question

we are working on a project, in which we have to replace html data with array values using PHP preg_replace()

please look at the codes

Codes

 $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;   

print the same $html, not updated.

Was it helpful?

Solution

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

should be:

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

Variables are only substituted inside double quotes, not single quotes.

Why are you using preg_replace when all your texts are ordinary strings? Why not str_replace?

You could also do all the replacements in one call. str_replace can take arrays of search and replacement strings:

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

or with regex you can use pipes to match all the words:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top