Making '/' bolded in preg_replace function

$string='"/" is a SLASH'; $bold='s'; $string1=preg_replace('/'.$bold.'/i','<b>\0</b>', $string);I have the code above and it produces the result below.

“/” iS a SLASH

And the code below produces “/” is a SLASH.

$bold='A'; $string2=preg_replace('/'.$bold.'/i','<b>\0</b>', $string);
So far so good

However,

$bold='/'; $string=preg_replace('/'.$bold.'/i','<b>\0</b>', $string);
when the variable $bold is “/” itself like the code above, it produces a warning saying the below

Warning: preg_replace() [function.preg-replace]: Unknown modifier '/'

How can I make the result like the below without warning.

 "<b>/</b>" iS a SLASH

Have you tried escaping it with a back slash?

\/
1 Like

[quote][quote=“Andres_Vaquero, post:2, topic:293348, full:true”]
Have you tried escaping it with a back slash?

/
[/quote]As I saw your suggest, I tried the code below.

$bold='/'; $string=preg_replace('\/'.$bold.'\/i','<b>\0</b>', $string);
But the result of the code above is the following.

preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash

How can I fix the code above?

You would have to escape the one in the variable $bold not the other ones.

[quote=“Andres_Vaquero, post:4, topic:293348, full:true”]
You would have to escape the one in the variable $bold not the other ones.
[/quote]As I tried the following code by your suggestion

$bold='\/'; string2=preg_replace('/'.$bold.'/i','<b>\0</b>', $string); It works fine.
Thank you, Andres_Vaquero.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.