March 31st, 2006
PHP - parse a string between two strings
This is a handy little function to strip out a string between two specified pieces of text. This could be used to parse XML text, bbCode, or any other delimited code/text for that matter.
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)

on September 20th, 2006 at 7:51 am
Thanks for this fine piece of work, I was exactly searching for this.
on November 13th, 2006 at 8:03 pm
This is a life saver!
on December 15th, 2006 at 9:05 am
This is a nice little function that I'm using to parse data from emails.
on December 30th, 2006 at 9:12 am
It´s a nice function, thanks!
on January 19th, 2007 at 1:16 pm
solved it perfectly. thanks.
on January 19th, 2007 at 1:29 pm
Glad it helped. You can always consider the $2 donation as mentioned above
on January 27th, 2007 at 8:04 pm
Great script…though, what if the string contains multiple instances of the same tag…a bold for example?
on January 28th, 2007 at 11:12 am
It will just parse the first instance. In which case, just add a third, optional parameter to indicate the starting character search position (int)
on February 9th, 2007 at 12:50 am
Greate script.It helps me a lot.
on May 25th, 2007 at 12:16 pm
Hi-I was wondering how it would be made to parse this string> "dog+cat+mouse+fish"
so that the result would be
"dogcatmousefish"
Thanks in advance.
on May 25th, 2007 at 12:25 pm
I think you'd have to use eregi for that
on May 26th, 2007 at 10:00 am
str_replace("+","","dog+cat+mouse+fish") = "dogcatmousefish"
on July 14th, 2007 at 8:46 am
Life saver.
on November 9th, 2007 at 10:11 pm
whoop! tanks!
on June 7th, 2008 at 11:45 am
I haven't tried this yet, but it looks like this function wouldn't work if $start appears at the very beginning of $string: strpos($string,$start) would return "0", which would make the function react as though strpos($string,$start) were "false" (ie, boolean 0), & thus the function would return "".
Perhaps using the === operator would solve this:
if ($ini === 0) return ""; would be evaluated as false if strpos($string,$start) returned "0" (as in "position zero"), but evaluated as "true" if strpos($string,$start) returned false (ie, boolean zero).
Does this make sense? (I'll need to give it a try to know for sure.)
I hope this helps.
Shane1010
on July 17th, 2008 at 10:53 am
super .) this is exactly what i need. thanks