preloaded image preloaded image preloaded image

PHP String Searching

Want to find some text between 2 known substrings within a PHP string? Here's how...

<?php 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 = "My name is Dave. I am 75 years of age."; $parsed_1 = get_string_between($fullstring, "My name is Dave. I am ", " years of age."); echo $parsed_1; ?>

This would return a string value equal to "75"

<?php 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 = "My name is Dave. I am 75 years of age."; $parsed_1 = get_string_between($fullstring, ". ", "."); echo $parsed_1; ?>

Notice the blank space after the period in the $start location -- this prevents the extra white space from being entered into our result. This would return a string value equal to "I am 75 years of age"

Now, this code also works in cases with less text specified, though we should be careful to only implement this with less text in the boundaries if we know it's safe. One such example would be within our own filepaths. If we have control over the original string (which we do for filepaths) we can use this same function and specify less information in the start/stop boundary text:

$fullstring = $_SERVER['PHP_SELF'];

Suppose this is known to be formatted as "/<directory>/<file_name>.<extension>"

Then to get the directory name in which a given index file resides we would do this:
$parsed = get_string_between($fullstring, "/", "/index");

This would return a string value equal to whatever the directory was. In the case of this page, it would return this value (which is itself being generated via PHP using this method):

php