Home >Backend Development >PHP Tutorial >How Can I Extract Substrings Between Delimiters in PHP Without Using Regular Expressions?
Retrieving Substrings Between Delimiters in PHP
While striving to obtain substrings enclosed within specific words or characters, you may ponder the availability of a PHP function dedicated to this task. Examining the strpos and substr functions, you seek an approach that bypasses regular expressions.
Solution:
You can indeed leverage the get_string_between function, crafted by Justin Cook. This function operates by locating the start and end positions of the substring within the provided string. Once identified, it utilizes substr to extract the desired substring.
Extended Functionality:
To extend the functionality of get_string_between, you can modify it to accept an array of delimiters. This allows you to retrieve multiple substrings between different pairs of delimiters.
Usage Example:
Consider the following string:
$string = "foo I like php foo, but foo I also like asp foo, foo I feel hero foo";
To obtain an array of substrings between "foo" delimiters, you would use:
$delimiters = ['foo', '/foo']; $innerSubstrings = get_string_between_multi($string, $delimiters);
Result:
The $innerSubstrings array will contain the following elements:
The above is the detailed content of How Can I Extract Substrings Between Delimiters in PHP Without Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!