2016-07-17 7 views
-1

私は秩序を保つ、別の文字列の言葉と文字列を一致させたい正規表現:私は結果がPHP、するpreg_match特定の単語0または1時間

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

一致文字列内のすべての単語は、元の順序で検索されるためです。 他の例:

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

のようなものでしょうか?ありがとうございました。

+0

私たちはあなたのコードを書いてください。 –

+0

@ダゴン私はコード全体を書いた、私は理解できない正規表現で助けが必要です。それは簡単な要求であり、スクリプト全体ではありません... –

+0

それは簡単です。 –

答えて

1

preg_matchの代わりにpreg_splitを使用することをおすすめします。また、あなたが検索する単語を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; 
} 
関連する問題