0

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.

Sam
  • 53
  • 1
  • 2
  • 9

1 Answers1

0
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);

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Ordinary strings means, the value can be different, it's user dependent. so please suggest me the which method is best for us ? thanks – Sam Oct 02 '12 at 09:21
  • Is the user allowed to give regex patterns like `a.*b` to match anything beginning with `a` and ending with `b`? Or are they just strings that should be matched exactly? – Barmar Oct 02 '12 at 09:26
  • we deals only with text, like if we match two website then duplicated words will be highlighted. we are just applied this script for. is there any other idea which is suitable for it ? – Sam Oct 02 '12 at 09:30