Making <br>'s compliant?

Hi, to try to get compliant code, I’m desperately trying to change the <br>'s into <br />'s - BUT, when trying to change this :

$stripped_file = preg_replace('/<br><b>(.*?)<p>/i','<br><p class="tops">$1</p><p class="gate">',$stripped_file);

Into this :

$stripped_file = preg_replace('/<br /><b>(.*?)<p>/i','<br /><p class="tops">$1</p><p class="gate">',$stripped_file);

I get errors - is it an escaping problem please?

Seems like you already know the answer.

The preg-replace is saying
OK, I’m enclosing my regex phrase with the forward slash character.
The regex engine looks for a second to end the enclosed phrase with.

Perhaps using a forward slash in the many exmples you’ll find was a bad choice.

In any case, you can either escape to make it a literal character or use a different character to enclose.

Many thanks Martin, it’s appreciated. Should I be putting more /'s in there somewhere please?

$stripped_file = preg_replace('/<br /><b>(.*?)<p>/i','<br /><p class="tops">$1</p><p class="gate">',$stripped_file);

The excape is a backwards slash - “\” - not an extra forward slash.

Lets put it in color so you see what preg is thinking. gets out crayons
Using / as delimiter:


Your code:

$stripped_file = preg_replace('[COLOR="Blue"]/[/COLOR][COLOR="Green"]<br[/COLOR] [COLOR="blue"]/[/COLOR][COLOR="DarkOrchid"]><b>(.*?)<p>/i[/COLOR]',[COLOR="Orange"]'<br /><p class="tops">$1</p><p class="gate">'[/COLOR],[COLOR="DarkRed"]$stripped_file[/COLOR]);

See where it’s getting hitched up?
PHP: Escape sequences - Manual

Thanks for the help. getting a little stuck on this and have looked through the manual. Should I be escaping the /'s?

You need to escape the /'s inside your pattern because they are the same as your delimiter. Either escape the /'s, or use a different delimiter.

It’s perfectly valid to do # as a delimiter, for example;
‘#<br /><b>(.*?)<p>#i’

is a perfectly valid pattern.

AFAIK you can use just about any character eg. if your regex had / and # in it you could use ~

IMHO its best to be consistant as much as possible - probably why all the doc examples use / - but sooner or later you’ll have one that gets messy looking with escapes and its easier to just use something different. eg.

“/<a href=\“http:\/\/domain\.com\”>/”
‘#<a href=“http://domain\.com”>#’

Many thanks Mittineague and StarLion - problem solved. :slight_smile: