Displaying a String Between Two Strings

Here is a a handy little function to display the text between two strings. This is useful when parsing XML, bbCode or even for creating article teasers for blogs or news articles.

Here is a a handy little function to display the text between two strings. This is useful when parsing XML, bbCode or even for creating article teasers for blogs or news articles:

function parseBetweenStrings($str,$start,$end) {
     $str = ” “.$str;
     $i = strpos($str,$start);

     if($i == 0) { return “”; };

     $i += strlen($start);
     $len = strpos($str,$end,$i) – $i;

     return substr($str,$i,$len);
}

For example, you would only like to dispay the red text from this string. We need to echo or print() the parseBetweenStrings() function. The first argument is the string variable, the second and third are the opening and the closing tags:

$str = “[color=red]This text is red[/color] [color=blue]This text is blue[/color]“;
echo parseBetweenStrings($str,”[color=red]“,”[/color”);

Once called, the function will return “This text is red”. Try it with other tags other than bbCode, such as HTML and XML.

09.10.03

Since I’m not very knowledgeable about computer jargon I’ll just say your article was as clear as mud to me. But I’m sure someone who knows what you’re talking about will find it helpful.
:)

comments powered by Disqus
Loading