My database has a table with 1000 terms and their definitions. I want to print those definitions and add a span tag to every word that is already a term.
I use this to create the two arrays (patterns and replacements):
while($row = mysql_fetch_array($rsd)){
$patterns[$i] = '/'.$row['term'].'/';
$patterns[$i+1] = '/<span class="linkedterm"><span class="linkedterm">'.$row['term'].'</span>/';
$replacements[$i+1] = '<span class="linkedterm">'.$row['term'].'</span>';
$replacements[$i] = '<span class="linkedterm">'.$row['term'];
$i = $i + 2;
}
And this to echo the definitions:
echo preg_replace($patterns, $replacements, $row['definition']);
Thanks
You might want to look at preg_quote
Quote regular expression characters
The / is also your delimiter character (to point out the start and end of your regex). So if you want to search for a literal /, make sure you escape it with a backslash, like so:
$patterns[$i+1] = '/<span class="linkedterm"><span class="linkedterm">'.$row['term'].'<\/span>/';
$patterns[$i] = '/'.preg_quote($row['term']).'/';
$patterns[$i+1] = '/'.preg_quote('<span class="linkedterm" ><span class="linkedterm" >'.$row['term'].'</span>', '/').'/';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.