PHP: How to extract string between 2 words


How to extract string between two words.

How to parse a string between two strings.

We offer 3 functions to obtain a string delimited between tags:

function string_Between($content, $start, $end)
{
    $r = explode($start, $content);
    if (isset($r[1]))
    {
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

function string_Between1($content, $start, $end)
{
    $matches = array();
    $start = preg_quote($start, '/');
    $end = preg_quote($end, '/');

    if (preg_match('/' . $start . '(.*?)' . $end . '/s', $content, $matches))
    {
        return $matches[1];
    } else
    {
        return 'No matches found!';
    }
}

function string_Between2($content, $start, $end = 0, $StartLoc = 0)
{
    if (($StartLoc = strpos($content, $start, $StartLoc)) === false)
    {
        return;
    }
    $StartLoc += strlen($start);
    if (!$end)
    {
        $end = $start;
    }
    if (!$EndLoc = strpos($content, $end, $StartLoc))
    {
        return;
    }
    return substr($content, $StartLoc, ($EndLoc - $StartLoc));
}

Example:

$str = 'blah<h2>tutorialspots.com | Free Online Tutorials | Tutorials, Resources and Snippets</h2>
dasd
dsadsd';

$time = microtime(true);
echo string_Between($str,'<h2>','</h2>');
$time = microtime(true) - $time;
echo "<br>";
echo $time;

echo "<br>";

$time = microtime(true);
echo string_Between1($str,'<h2>','</h2>');
$time = microtime(true) - $time;
echo "<br>";
echo $time;

echo "<br>";

$time = microtime(true);
echo string_Between2($str,'<h2>','</h2>');
$time = microtime(true) - $time;
echo "<br>";
echo $time;

Result:

tutorialspots.com | Free Online Tutorials | Tutorials, Resources and Snippets
6.31809234619E-5
tutorialspots.com | Free Online Tutorials | Tutorials, Resources and Snippets
9.01222229004E-5
tutorialspots.com | Free Online Tutorials | Tutorials, Resources and Snippets
2.90870666504E-5

We notice that function string_Between2 is the fasted way to parse a string between two strings.

Leave a Reply