Skip to content

Instantly share code, notes, and snippets.

@hearvox
Created January 11, 2019 20:30
Show Gist options
  • Save hearvox/e56ba77ebf9a06f131a6aa347c071b07 to your computer and use it in GitHub Desktop.
Save hearvox/e56ba77ebf9a06f131a6aa347c071b07 to your computer and use it in GitHub Desktop.
Get a string between two specified strings (can parse XML, HTML, or other code/text).
<?php
// @ see: http://www.justin-cook.com/2006/03/31/php-parse-a-string-between-two-strings/
function get_string_between( $string, $start, $end){
$string = " " . $string; // Convert to string.
$ini = strpos( $string, $start ); // Position of start text.
if ($ini == 0) {
return "";
}
$ini += strlen( $start ); // Length of start text.
$len = strpos( $string, $end, $ini) - $ini; // Position of end text.
return substr( $string, $ini, $len); // String betwen start and end.
}
/*
Example:
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment