2012-02-23 3 views
14
$string = ":abc and :def have apples."; 
$replacements = array('Mary', 'Jane'); 

になる必要があります。にpreg_replace

Mary and Jane have apples. 

を今私はこのようにそれをやっている:

preg_match_all('/:(\w+)/', $string, $matches); 

foreach($matches[0] as $index => $match) 
    $string = str_replace($match, $replacements[$index], $string); 

私は、単一の実行でこれを行うことができ、にpreg_replaceのようなものを使用して?

+1

は、[この](http://codepad.org/KfP3g02m)あなたは連想配列でそれを行うことができる方法です。 – Teneff

答えて

10

あなたはあなたの交換次々消費コールバックでpreg_replace_callbackを使用することができます。のために

Mary and Jane have apples. 
+0

e修飾子はPHP v.5.5以降で償却されました – Kareem

+1

@Karim:そうです、答えから削除しました。ポインタありがとう。 – hakre

8
$string = ":abc and :def have apples."; 
$replacements = array('Mary', 'Jane'); 

echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string); 

出力を乗算電子とあなたが正規表現パターンと一致するようにこれを使用することができ連想キーによる全配列の交換:

$words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow"); 
    $source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ ... _animal_sound_ , _no_match_"; 


    function translate_arrays($source,$words){ 
    return (preg_replace_callback("/\b_(\w*)_\b/u", function($match) use ($words) { if(isset($words[$match[0]])){ return ($words[$match[0]]); }else{ return($match[0]); } }, $source)); 
    } 


    echo translate_arrays($source,$words); 
    //returns: Hello! My Animal is a cat and it says MEooow ... MEooow , _no_match_ 

を*お知らせは、「_no_match_」は翻訳を欠いているが、それは正規表現の間に一致しますが、 そのキーを保持しますthatsの。また、キーは何度も繰り返すことができます。

+0

これはHHVMの回避策では動作しませんか? – Mario

3

$string = ":abc and :def have apples."; 
$replacements = array('Mary', 'Jane'); 
echo preg_replace_callback('/:\w+/', function($matches) use (&$replacements) { 
    return array_shift($replacements); 
}, $string); 

出力:

Mary and Jane have apples. 
+0

UTF-8文字列をサポートする正規表現に "/ \ b _(\ w *)_ \ b/u'という" u "修飾子を追加することをお勧めします。ところで、上記のコードには構文エラーがあり、最後に余分な括弧があります。 – nikoskip

+0

余分な括弧の問題のように見える、私はコードを確認し、okを実行しています。私はUTf-8を追加しました。 – Miguel

6

ここでこの

$to_replace = array(':abc', ':def', ':ghi'); 
$replace_with = array('Marry', 'Jane', 'Bob'); 

$string = ":abc and :def have apples, but :ghi doesn't"; 

$string = strtr($string, array_combine($to_replace, $replace_with)); 
echo $string; 

が結果です試してみてください。http://sandbox.onlinephpfunctions.com/code/7a4c5b00f68ec40fdb35ce189d26446e3a2501c2

+1

これは正規表現を使用しないため、これが最速の解決策です – Drakes