Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: trim br tags from the beginning of a string?

Tags:

regex

php

I know that:

preg_replace('<br\s*\/?>', '', $string);

will remove all br tags from $string...

How can we remove all <br><br/><br /> tags only if they are in the very beginning of $string? ($string in my case is html code with various tags...)

like image 816
Thanos Avatar asked May 14 '10 12:05

Thanos


People also ask

How to remove br tag from string in PHP?

The line break can be removed from string by using str_replace() function.

What is trim PHP?

The trim() function in PHP is an inbuilt function which removes whitespaces and also the predefined characters from both sides of a string that is left and right.


1 Answers

Just add an appropriate anchor (^):

preg_replace('/^(?:<br\s*\/?>\s*)+/', '', $string);

This will match multiple <br>s at the beginning of the string.

(?:…) is a non-capturing group since we only use the parentheses here to group the expression, not capture it. The modifier isn’t strictly necessary – (…) would work just as well, but the regular expression engine would have to do more work because it then needs to remember the position and length of each captured hit.

like image 76
Konrad Rudolph Avatar answered Sep 22 '22 08:09

Konrad Rudolph