Tags
Asked 2 years ago
17 Jun 2021
Views 196
Kurt

Kurt posted

How to get a substring between two strings in PHP?

How to get a substring between two strings in PHP?
noob

noob
answered Apr 27 '23 00:00

To get a substring between two strings in PHP, you can use the strpos () and substr () functions together.

Here's an example of how to do it:


f

unction getSubstringBetween($string, $start, $end) {
    $startPosition = strpos($string, $start);
    if ($startPosition === false) {
        return "";
    }

    $startPosition += strlen($start);
    $endPosition = strpos($string, $end, $startPosition);
    if ($endPosition === false) {
        return "";
    }

    return substr($string, $startPosition, $endPosition - $startPosition);
}

This function takes three parameters: $string, which is the original string you want to search in, $start, which is the string you want to start the substring from, and $end , which is the string you want to end the substring at.

The function first finds the position of the $start string using strpos(). If $start isn't found, the function returns an empty string.

If $start is found, the function adds the length of $start to find the starting position of the substring, and then uses strpos() again to find the ending position of the substring. If $end isn' t found, the function returns an empty string.

If both the starting and ending positions are found, the function uses substr() to extract the substring between the two positions, and then returns it.

Here's an example of how to use the function:



$string = "This is a sample string to get substring from";
$start = "sample";
$end = "from";
$substring = getSubstringBetween($string, $start, $end);
echo $substring; // Outputs " string to get substring "

In this example, we define a string $string , and two variable s $start and $end . We then call the getSubstringBetween () function with these three arguments to get the substring between $start and $end. The resulting substring is then printed to the screen using echo.
Post Answer