Take what's between [code][/code] and apply ch

2019-08-03 06:39发布

问题:

I want to make code box, where I can apply changes. If I have this: $var= "word"; inside these [code] HERE [/code], I will change $var into red color and "word" into green.

I used preg_replace to select what's between these [code] [/code].

$codebox = preg_replace("/\[code\](.*?)\[\/code\]/","$1",$string);

the thing is with preg_replace I can do outsider changes (to whole code). I want to do changes to what inside these [code] [/code]. Like: background color, all text color, all text font, all text font-weight and etc... that's mean I need to get it out apply changes then put it back.

I want to be able to use str_replace and preg_replace functions on $1 not on $string.

for example to change"word" into green. I'll use

preg_replace("/(\".*?\")/","<span style='color: #090;'>$1</span>",$string)

and I can't use preg_replace inside preg_replace, can I? I don't know if I'm using the wrong function here, or there is a way do this.

you may find my patterns wrong, correct me I just learnt them yesterday.

回答1:

Using preg_replace_callback:

$string = '[code]$var = "word";[/code]';
$codebox = preg_replace_callback("/\[code\](.*?)\[\/code\]/",function($m){
    // The following replacements are just a demo
    $m[1] = preg_replace('/"([^"]+)"/', '"<span style="color:#0D0;">$1</span>"', $m[1]); // green value
    $m[1] = preg_replace('/(\$\w+)/', '<span style="color:#F00;">$1</span>', $m[1]); // Red var name
    $m[1] = str_replace(' = ', '<span style="color:#00F;"> = </span>', $m[1]); // blue = sign
    return $m[1];
},$string);
echo $codebox;

Online demo.



回答2:

Targeting the code inside the tags is a bit simpler when you extract it first using preg_match instead of preg_replace:

$codebox = preg_match("/\[code\](.*)\[\/code\]/",$string,$matches);
$innercode = $matches[0];

// Then...

$innercode = preg_replace( ...

// Later on...

echo "[code]".$innercode."[/code]";

Your replaces return strings, so they can be nested just fine.

Also, I suggest looking at a text to regex converter if you're new to regular expressions. It helped me get a grasp on them better:

http://txt2re.com/index-php.php3?s=$bacon%20=%20%22good%22;&-21&2&6&-23&7&1&-22