简体   繁体   中英

How to replace some words in bracket with html tag in PHP?

I'm trying to replace some words between bracket with html tag. Thing I have is,

$string = "Please make it (yellow)! (Red) also ok. I think, you like (blue)";

Thing I want is,

$string = "Please make it <span class='font-bold'>(yellow)</span>! <span class='font-bold'>(Red)</span> also ok. I think, you like <span class='font-bold'>(blue)</span>";

If I would like to replace text not only in brackets, but also in something like , how can I do?,我该怎么办?

You'll want to become familiar with str_replace ( http://php.net/manual/en/function.str-replace.php ).

Here's how you would do it:

$pattern = ["(",")"];
$replace = ["<span class='bold-face'>(",")</span>"];

$newstring = str_replace($pattern, $replace, $string);

Also check out preg_replace ( http://php.net/manual/en/function.preg-replace.php ) for regular expression string replacements for even more flexibility.

Actually it's your task and you should try to solve it first before asking, and should provide what you have done so far.

Basically you have to find () with text in the middle, the best way is using regular expression pattern to find it.

Here solution using preg_replace

$string = 'Please make it (yellow)! (Red) also ok. I think, you like (blue)';
$pattern = '/(\(\w+\))/';
$replacement = '<span class=="font-bold=">${1}</span>';
echo preg_replace($pattern, $replacement, $string);

for [] {} QQ change pattern to this /(\\(\\w+\\)|\\[\\w+\\]|{\\w+}|Q\\w+Q)/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM