Removing start and end tags in PHP

Quick question:

What is the best way to remove the tag <br>

and <br />

from the beginning and the end $string

?

I am currently using this code, but it doesn’t only remove tags <br>

.

$str = preg_replace('{^(<br(\s*/)?>|ANDnbsp;)+}i', '', $str);
$str = preg_replace('{(<br(\s*/)?>|ANDnbsp;)+$}i', '', $str);

      


EDIT: More information

This code deals with information that was imported from the old CMS.

As such, I know that the only two tags I need to replace are <br>

and <br />

. Also, I just want to replace those tags at the very beginning and at the very end $string

, not in between.

I don't need to deal with other tags; garbled HTML and additional attributes.

Basically, I would just like to expand on the code I suggested to replace tags <br>

as well <br />

.

Apologies for not offering enough information to get you started.


Thanks in advance,

+3


source to share


2 answers


One of the possibilities of a regular expression is this:

"/(^)?(<br\s*\/?>\s*)+$/"

      

So let's make it clear:

$str = preg_replace("/(^)?(<br\s*\/?>\s*)+$/", "", $str);

      



Clarification:

  • * - Matches 0 or more times;
  • \ s - Matches any space character;
  • ? - match 0 or 1 time; or: shortest match;
  • ^ - Matches only at the beginning of a line;
  • $ - Matches only at the end of the line;

A Good Starting Point: Perl Regular Expressions

+3


source


You shouldn't use Regex to parse html.

If you get a regex that matches <br />

and <br>

what happens if someone chooses style

, class

or id

? If you write this, what if they write the headline? or just paste some poorly formatted code?



You have to use the function strip_tags()

here .

Or a DOM parser here .

+2


source







All Articles