Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php,regex preg_匹配特定单词0或1次_Php_Regex_Pattern Matching_Match - Fatal编程技术网

php,regex preg_匹配特定单词0或1次

php,regex preg_匹配特定单词0或1次,php,regex,pattern-matching,match,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 = "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');
我的魔法函数是这样的

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;
}
对regex部分有什么帮助吗?谢谢。

我建议使用preg\u match,而不是
preg\u match
。也要确保转义你搜索的单词。我还建议将单词边界条件(
\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;
}
函数魔法函数($string\u original,$match\u string){
foreach(分解(“”,$match_字符串)为$word){
$word=preg_quote($word);
$split=preg_split(“/\b$word\b/”,$string_original,2);
如果(计数($split)<2)中断;
$result[]=$word;
$string_original=$split[1];
}
返回$result;
}

我们不能很好地响应为您编写代码的请求。@Dagon我写了全部代码,我只是需要一个我无法理解的regexp的帮助。这是一个简单的请求,不是一个完整的脚本…那么它很简单…以防万一。。。