PHP: Find text between two strings without regex


Written by

So today, my friend asked me for some regex to get text between two given strings; I can’t do regex so I came up with a simple line of code and then turned it into a function so it can be re-used.

I thought I’d pop the code here for others too.

/***************************************************************
 * @title:        Lazy Regex
 * @descr:        Find any text between two strings.
 * @author:        Adam Boutcher
 * @email:        admin@aboutcher.co.uk
 * @web:        www.aboutcher.co.uk
 * @usage:
 *                string lazy_regex (string $haystack, string $needle_first, string $needle_last)
 * @Params:        
 *                $haystack - the text you which to search
 *                $needle_first - Find this text as the start of the pointer.
 *                $needle_first - Find this text as the end of the pointer.
 * @notes:        
 *                Returns false on failure, this maybe non-bool false, use === to test (see PHP: substr).
 *                Returns the start and end needles including the text beween on success.
 **************************************************************/

function lazy_regex($haystack, $needle_first, $needle_last) {
    if ((empty($haystack))||(empty($needle_first))||(empty($needle_last))) { return false; }
    return substr($haystack, stripos($haystack, $needle_first), ((stripos($haystack, $needle_last)+strlen($needle_last))-stripos($haystack, $needle_first)));
}