tags:

views:

246

answers:

3

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...)

+3  A: 

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.

Konrad Rudolph
you'll be needing delimiters around your regex and since nothing needs to be captured, use a non-capturing group `(?:...)`
salathe
@salathe: Yup … I’ve added them. I just copied the question’s code at first, that’s why I forgot them. – And the non-capturing group is a good idea, too.
Konrad Rudolph
thanks for the anchor tip, that's what I was missing... your regex doesn't remove all occurrences but combined with this post: http://stackoverflow.com/questions/133571/how-to-convert-multiple-br-tag-to-a-single-br-tag-in-php the correct regex should be /^(<br\s*\/?>\s*)+/change it and I'll mark the answer as accepted
Thanos
@Thanos: Well, from your question it sounded as though there were no whitespaces between the `<br>`s …
Konrad Rudolph
ok sorry my mistake... thanks again.
Thanos
A: 

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
Gumbo
A: 
$string = preg_replace( '@^(<br\\b[^>]*/?>)+@i', '', $string );

Should match:

<br>
<br/>
<br style="clear: both;" />
etc
Salman A