Home >Backend Development >PHP Tutorial >How to Extract Substrings Between Delimiters in PHP?

How to Extract Substrings Between Delimiters in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-03 06:46:39477browse

How to Extract Substrings Between Delimiters in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn