PHP - parse a string between two strings
![Justin Cook](/assets/blog/authors/jc.jpg)
Justin Cook
![Cover Image for PHP - parse a string between two strings](/_next/image?url=%2Fassets%2Fblog%2Fphp-parse-between-strings%2Fcover.jpg&w=3840&q=75)
![Justin Cook](/assets/blog/authors/jc.jpg)
Justin Cook
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.
Here's the code
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);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)