How to strip multiple sections from a string in PHP

Take the following string:

Out in the west Texas town of El Paso
I fell in love with a Mexican girl
Night time would find me in Rosa’s Cantina
Music would play and Felina would whirl

Which is created in raw HTML like this:

Let’s say you want to strip all the sections from this string that are enclosed in boldface tags, including the tags themselves, so that you get this string:

Out in the west Texas town of El Paso
Night time would find me in Rosa’s Cantina

This PHP function will do the job:

function strip_tag_content($string, $start, $end) {

while (true) {
$ini = strpos($string,$start);
if ($ini === false) return $string;
$len = strpos($string,$end,$ini) + strlen($end) – $ini;
$sub = substr($string,$ini,$len);
$string = str_replace($sub,”\n\n”,$string);
}
return $string;

}

Like so:

$s = ‘Out in the west Texas town of El Paso<br /> <b>I fell in love with a Mexican girl</b><br /> Night time would find me in Rosa’s Cantina<br /> <b>Music would play and Felina would whirl</b><br />’;

$s = strip_tag_content($s,’<b>’,'</b>’);

Explanation:

The function accepts the raw string and the tag identifiers as arguments.

It then finds the position of the first letter of the $start argument in the raw string. If no position is found, the raw string is returned in its current state.

If a position is found, the function then calculates the length of the substring that begins at the first letter of the $start argument, and ends at the last letter of the $end argument.

The function then uses the strpos PHP function to create a variable from that substring.

The function then uses the str_replace PHP function to replace that substring with 2 newline characters (or whatever you want to replace it with).

The while wrapper perpetuates this process until no position is found for the $start variable (ie when all instances of the tags have been removed).

So how does this differ from the PHP striptags function?

The standard PHP striptags function will only strip the tags themselves. This function will string the tags and everything between the tags. You can also use this function to strip string parts based on delimiters other than HTML tags.

And now ladies and gentleman, Mr. Marty Robbins:

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>