Finding Substrings Between Delimiters in PHP
Developers often encounter the need to extract substrings sandwiched between specific delimiters. PHP offers a straightforward method to accomplish this task without resorting to complex regular expressions.
GetInnerSubstring Function
To simplify the process, PHP developers can leverage the strpos and substr functions to create a customized getInnerSubstring function. Here's how it works:
Extension to Multiple Delimiters
The getInnerSubstring function can be extended to handle multiple occurrences of the same delimiter, separating them into an array. Here's the modified code:
function getInnerSubstring($string, $delim) { $start_pos = strpos($string, $delim); $result = array(); while ($start_pos !== false) { $end_pos = strpos($string, $delim, $start_pos + strlen($delim)); if ($end_pos === false) break; $result[] = substr($string, $start_pos + strlen($delim), $end_pos - $start_pos - strlen($delim)); $start_pos = strpos($string, $delim, $end_pos); } return $result; }
Example Usage:
$string = "foo I like php foo, but foo I also like asp foo, foo I feel hero foo"; $result = getInnerSubstring($string, "foo"); print_r($result); // Output: [" I like php ", " I also like asp ", " I feel hero "]
This extended version allows you to retrieve an array of substrings located between any number of delimiter occurrences.
The above is the detailed content of How Can I Efficiently Extract Substrings Between Delimiters in PHP?. For more information, please follow other related articles on the PHP Chinese website!