如何在PHP中用html标签替换%

如何在PHP中用html标签替换%

问题描述:

I have the following code in PHP:

$fullString = "a %sample% word go %here%";

And I want to replace % with html tag (<span style='color:red'> and </span>). This is what I want after replacing:

$fullString ="a <span style='color:red'>sample</span> word go <span style='color:red'>here</span>";

What should I do to accomplish this result using PHP function like str_replace, preg_replace etc.? Thanks.

You could do....

$string = "a %sample% word go %here%";
echo preg_replace('~%(.*?)%~', '<span style="color:red">$1</span>', $string);

That says replace everything between the first % and next occurring % sign with the spans. The () groups everything inside those percents into the $1.

Output:

a <span style="color:red">sample</span> word go <span style="color:red">here</span>