php,regex preg_match一个特定的单词0或1次

时间:2016-07-17 21:27:50

标签: php regex pattern-matching match

我希望将字符串与另一个字符串的字符匹配,保持顺序:

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

我希望结果是

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

因为匹配字符串中的所有单词都在原始排序中找到。 另一个例子:

$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');

我的magic_function类似于

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;
}

有关正则表达式部分的任何帮助吗?谢谢。

1 个答案:

答案 0 :(得分:1)

我建议使用preg_split代替preg_match。另外,请确保使用preg_quote转义您搜索的字词。我还建议在正则表达式中添加单词边界条件(\b),因此只匹配完整单词。如果你想匹配部分词语,请把它拿出来:

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;
}