Franz Tesca Franz Tesca - 4 months ago 30
PHP Question

php, regex preg_match a specific word 0 or 1 time

I want to match a string with the words of another string, keeping the order:

$string_original = "Number three is good, then two and one.";
$match_string = "three two one";
$result = magic_function($string_original,$match_string);


I want the result to be

$result = array(0 => 'three', 1 => 'two', 2 => 'one');


Because all the words in the match string are found in the original ordered.
An other example:

$string_original = "two is a magic number, one also and three";
$match_string = "three two one";
$result = magic_function($string_original,$match_string);
//RESULT WOULD BE
$result = array(0 => 'three');

//LAST EXAMPLE
$string_original = "three one, then two!";
$match_string = "three two one";
$result = magic_function($string_original,$match_string);
//RESULT WOULD BE
$result = array(0 => 'three', 1 => 'two');


My magic_function is something like

function magic_function($origin,$match){
$exploded = explode(' ',$match);
$pattern = '/';
foreach ($exploded as $word){
$pattern .= '';//I NEED SOMETHING TO PUT HERE, BUT MY REGEX IS PRETTY BAD AND I DON'T KNOW
}
$pattern .= '/';
preg_match($pattern,$origin,$matches);
return $matches;
}


Any help with the regex part? Thank you.

Answer

I would suggest using preg_split instead of preg_match. Also make sure to escape words you search for with preg_quote. I also suggest adding word boundary conditions (\b) to the regular expressions, so you only match complete words. Take that out if you want to match part of words:

function magic_function($string_original,$match_string) {
    foreach(explode(' ', $match_string) as $word) {
        $word = preg_quote($word);
        $split = preg_split("/\b$word\b/", $string_original, 2);
        if (count($split) < 2) break;
        $result[] = $word;
        $string_original = $split[1];
    }
    return $result;
}