Xeer
Xeer

Reputation: 11

Preg_replace change chars

I have a problem with the function preg_replace.

How replace chars [ to &1; and ] to &2;

When first is tag [cd] and last tag is [/cd]?

input:

[cd]H[o]m[/cd]

output:

[cd]H&1;o&2;[/cd]

I tried:

preg_replace('#\[cd\]([\s\S]*?)\[\/cd\]#i', '[cd]\1[/cd]', '[cd]H[o]m[/cd]');

Thank you in advance for your help!

Upvotes: 0

Views: 30

Answers (1)

Barmar
Barmar

Reputation: 780949

If you want to make changes to a captured string, you can use preg_replace_callback(). This calls a function instead of using a simple string as the replacement.

$string = preg_replace_callback('#\[cd\]([\s\S]*?)\[/cd\]#i', function($matches) {
    $str = str_replace(array('[', ']'), array('&1', '&2'), $matches[1]);
    return "[cd]{$str}[/cd]";
}, '[cd]H[o]m[/cd]');

BTW, you don't need to escape / in the regexp if you're using a different character as the delimiter -- that's the reason you used # as the delimiter.

Upvotes: 2

Related Questions