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...)
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...)
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.
You forgot the delimiters for PCRE in your regular expression. Try this:
$string = preg_replace('/^\s*(?:<br\s*\/?>\s*)*/i', '', $string);
This will also remove leading whitespace characters before, between and after the line break tags.
Some explanation:
^\s* will match any whitespace characters at the start of your string(?:<br\s*\/?>\s*)* will match zero or more occurrences of BR tags (both HTML and XHTML) followed by optional whitespace characters$string = preg_replace( '@^(<br\\b[^>]*/?>)+@i', '', $string );
Should match:
<br>
<br/>
<br style="clear: both;" />
etc