PHP – String Parser, Find a String Between Two Strings
October 31st, 2009By Ryan Huff
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);
}
//USAGE
echo get_string_between(“this is a test”, “this “, ” a test”); //RETURNS ’is’
This is a very handy and easy to implement utility for PHP. Simply call the function as shown in order to get the string value between to known string points.
There are three variables that you need to pass to the function, the target text, the left data point and finally the right data point; in that order as well. The return of the function call is the string value that is between your two data points. It is important to note that the space character, ” ” counts as a valid character so keep that in mind or you’ll lose sleep over trying to figure out why it isn’t working only to realize that you didn’t account for a space somewhere!
The mechanics here are very simple. First, find the integer position of the the left point and then add that to the total length. Next find the integer position of the right data point starting at the integer position equal to the length of the left point and then subtract that by the total length of the left.
Lastly, return the original string starting at the end of the length of the left string point and ending at the beginning of the right string point.
|
Ryan Huff is an Internet Marketing and technology coach specializing in start-up business development. You can connect with Ryan at http://mycodetree.com or follow Ryan at http://twitter.com/rthconsultants Article Source: http://EzineArticles.com/?expert=Ryan_Huff |





