php, regex preg_match a specific word 0 or 1 time <p>I want to match a string with the words of another string, keeping the order:</p> <pre><code>$string_original = "Number three is good, then two and one."; $match_string = "three two one"; $result = magic_function($string_original,$match_string); </code></pre> <p>I want the result to be</p> <pre><code>$result = array(0 =&gt; 'three', 1 =&gt; 'two', 2 =&gt; 'one'); </code></pre> <p>Because all the words in the match string are found in the original ordered. An other example:</p> <pre><code>$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 =&gt; '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 =&gt; 'three', 1 =&gt; 'two'); </code></pre> <p>My magic_function is something like</p> <pre><code>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; } </code></pre> <p>Any help with the regex part? Thank you.</p>