Extract String Between in PHP: Guide

In PHP, you can use the functions strpos() and substr() to extract the content between two strings. Here is an example code:

function getStringBetween($str, $start, $end){
    $startPos = strpos($str, $start);
    $endPos = strpos($str, $end);
    
    if($startPos === false || $endPos === false){
        return false;
    }
    
    $startPos += strlen($start);
    
    return substr($str, $startPos, $endPos - $startPos);
}

$str = "Hello, [World]!";
$start = "[";
$end = "]";
$result = getStringBetween($str, $start, $end);
echo $result; // Output: World

In this example, the function getStringBetween() takes three parameters: the original string $str, the starting string $start, and the ending string $end. The function uses the strpos() function internally to find the positions of the starting and ending strings in the original string, then uses the substr() function to extract the content between the two strings and returns the result.

bannerAds