How to Extract Substrings Between Specified Delimiters in PHP
For scenarios where you need to obtain the substring located between two specific strings, PHP provides convenient functions to accomplish this task.
To extract a substring between two strings, such as 'foo' and 'foo', utilize the following function:
function getInnerSubstring($string, $delim) { $start = strpos($string, $delim); if ($start === false) { return ''; } $end = strpos($string, $delim, $start + strlen($delim)); if ($end === false) { return ''; } return substr($string, $start + strlen($delim), $end - $start - strlen($delim)); }
An example usage and result:
$string = "foo I wanna a cake foo"; $substring = getInnerSubstring($string, "foo"); echo $substring; // Output: " I wanna a cake "
For a more advanced use case, you can extend the function to retrieve multiple substrings enclosed within multiple delimiter pairs. Consider the following example:
$string = "foo I like php foo, but foo I also like asp foo, foo I feel hero foo"; $result = getInnerSubstrings($string, "foo"); echo json_encode($result); // Output: ["I like php", "I also like asp", "I feel hero"]
In this updated function, we introduce a loop to iterate through the string and collect all substrings matching the specified delimiters. The function returns an array of substrings.
The above is the detailed content of How to Extract Substrings Between Delimiters in PHP?. For more information, please follow other related articles on the PHP Chinese website!