How to get string between two string in php?

A vast majority of answers here don't answer the edited part, I guess they were added before. It can be done with regex, as one answer mentions. I had a different approach.


This function searches $string and finds the first string between $start and $end strings, starting at $offset position. It then updates the $offset position to point to the start of the result. If $includeDelimiters is true, it includes the delimiters in the result.

If the $start or $end string are not found, it returns null. It also returns null if $string, $start, or $end are an empty string.

function str_between(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?string
{
    if ($string === '' || $start === '' || $end === '') return null;

    $startLength = strlen($start);
    $endLength = strlen($end);

    $startPos = strpos($string, $start, $offset);
    if ($startPos === false) return null;

    $endPos = strpos($string, $end, $startPos + $startLength);
    if ($endPos === false) return null;

    $length = $endPos - $startPos + ($includeDelimiters ? $endLength : -$startLength);
    if (!$length) return '';

    $offset = $startPos + ($includeDelimiters ? 0 : $startLength);

    $result = substr($string, $offset, $length);

    return ($result !== false ? $result : null);
}

The following function finds all strings that are between two strings (no overlaps). It requires the previous function, and the arguments are the same. After execution, $offset points to the start of the last found result string.

function str_between_all(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?array
{
    $strings = [];
    $length = strlen($string);

    while ($offset < $length)
    {
        $found = str_between($string, $start, $end, $includeDelimiters, $offset);
        if ($found === null) break;

        $strings[] = $found;
        $offset += strlen($includeDelimiters ? $found : $start . $found . $end); // move offset to the end of the newfound string
    }

    return $strings;
}

Examples:

str_between_all('foo 1 bar 2 foo 3 bar', 'foo', 'bar') gives [' 1 ', ' 3 '].

str_between_all('foo 1 bar 2', 'foo', 'bar') gives [' 1 '].

str_between_all('foo 1 foo 2 foo 3 foo', 'foo', 'foo') gives [' 1 ', ' 3 '].

str_between_all('foo 1 bar', 'foo', 'foo') gives [].

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    A string is a sequence of characters stored in the incremental form in PHP. A set of characters, one or many can lie between any two chosen indexes of the string. The text between two characters in PHP can be extracted using the following two methods : 

    Approach 1: Using substr() Method: The substr() method is used to retrieve a substring of the original string. It takes as indexes the start and end indexes and extracts the part of the string lying between the indexes. In order to retrieve the substring from the beginning, the start-index is chosen to be 0. 

    substr(string, startIndex, lengthStr)

    Parameters: 

    • string: In this parameter, we pass the original string or the string that needs to be cut or modified. It is a mandatory parameter.
    • startIndex: It refers to the position of the original string from where the part needs to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of the position in the string from the beginning. If the integer is negative then it refers to the start of the position from the end of the string. This is also a mandatory parameter.
    • lengthStr: It is an optional parameter of integer type. It refers to the length of the part of the string that needs to be cut from the original string. If the integer is positive, it refers to start from start_position and extract length from the beginning. If the integer is negative then it refers to start from start_position and extract the length from the end of the string. If this parameter is not passed, then the substr() function will return the string starting from start_position till the end of the string.

    PHP

    $str = "Hi! This is geeksforgeeks";

    echo("Original String : ");

    echo($str . "\n");

    $final_str = substr($str, 4, 7);

    echo("Modified String : ");

    echo($final_str);

    ?>

    Output

    Original String : Hi! This is geeksforgeeks
    Modified String : This is

    Approach 2: Using for loop and str_split() Method: The str_split() method is used to split the specified string into an array, where the elements are mapped to their corresponding indexes. The indexes of the array begin with 0. 

    array_split( string )

    A loop iteration is performed over the array length. Every time the iteration is performed the index is checked if it lies between the start and end index. If it lies in the range, the character is extracted.  

    PHP

    $str = "Hi! This is geeksforgeeks";

    echo("Original String : ");

    echo($str . "\n");

    $start = 5;

    $end = 8;

    $arr = str_split($str);

    echo("Modified String : ");

    for($i = 0; $i < sizeof($arr); $i++) {

        if($i >= $start && $i <= $end) {

            print($arr[$i]);

        }

    }

    ?>

    Output

    Original String : Hi! This is geeksforgeeks
    Modified String : his 


    How do you get a string between?

    Test String test string (67) from which you need to get the String which is nested in-between two Strings..
    String str = "test string (67) and (77)", open = "(", close = ")";.
    String subStr = str..

    What is splitting in PHP?

    Definition and Usage The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.

    What is Strstr PHP?

    The strstr() function searches for the first occurrence of a string inside another string. Note: This function is binary-safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr() function.

    What is substring in PHP?

    What is substr in PHP? substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.