2010-12-01 17 views
0

こんにちはすべて私はPHPの文字列の特定のタイプを交換する必要があります。 私は単語を2つの異なる単語に置き換える必要があります。文字列をphpに置き換えます - より多くの単語に1つの単語

たとえば、「Hi mom、hi dad」の文字列では、「hi」という単語を「mary」や「john」などの2つの異なる単語に自動的に置き換える必要があります。したがって、 "Hi"が1つしか出現しない場合、 "mary"と置き換えられますが、複数の単語がある場合は、すべての単語の関連付けを使用します。

したがって、1語は、単語の出現回数に基づいて置き換えられます。 私を助けることができるすべての人に感謝!

+0

一つの疑問B、ホードは、「こんにちはお母さん、こんにちはお父さんを持って言うことができます、hi grampa "それはメアリーとジョンで再び始まるか、それともピーターになるだろうか? – Trufa

答えて

3

preg_replace_callbackを使用すると、それぞれの置換えを制御できます。

+1

これはあなたが私に尋ねるとあなたの問題を解決する方法です。私の例を見て、あなたが探しているものの作業バージョンを見てください。 (+1) – Michael

0

あなたは、各コールのための1の制限値を指定して、preg_replaceへの複数の呼び出しでこれを達成することができます:

$string = "Hi mom, hi dad"; 

preg_replace('/hi/i', 'mary', $str, 1); // "mary mom, hi dad" 
preg_replace('/hi/i', 'john', $str, 1); // "mary mom, john dad" 

あなたは次のようなものでこれを一般化することができます。これは、件名、パターン、および1つ以上の置換単語を取ります。

function replace_each($subject, $pattern, $replacement) { 

    $count = 0; 
    for ($i = 2; $i < func_num_args(); ++$i) { 
    $replacement = func_get_arg($i); 
    $subject = preg_replace($pattern, $replacement, $subject, 1, $count); 
    if (!$count) 
     // no more matches 
     break; 
    } 
    return $subject; 
} 

$string = preg_replace_each("Hi mom, hi dad", "/hi/i", "mary", "john"); 

echo $string; // "mary mom, john dad" 
0

preg_replace_callbackは別の$の制限を利用することであると$にpreg_replaceのパラメータを数え、一つの方法である(manpageを参照)

$str = "hi foo hi bar hi baz hi quux"; 
$repl = array('uno', 'dos', 'tres'); 

do{ 
    $str = preg_replace('~hi~', $repl[0], $str, 1, $count); 
    $repl[] = array_shift($repl); // rotate the array 
} while($count > 0);  
0

私はそれを行うには本当に簡単な方法があるかどうかわかりません私が書いたこのコードを見てみましょう。これはあなたのためにトリックを行う必要があります:)

<?php 
class myReplace{ 
    public $replacements = array(); 
    protected $counter = 0; 

    public function __construct($replacements) { 
     // fill the array with replacements 
     $this->replacements = $replacements; 
    } 

    public function test($matches) { 
     // if you want you could do something funky to the matches array here 

     // if the key does not exists we are gonna start from the first 
     // array element again. 
     if(!array_key_exists($this->counter, $this->replacements)) { 
     $this->counter = 0; 
     } 

     // this will return your replacement. 
     return $this->replacements[$this->counter++]; 
    } 
} 

// Instantiate your class here, and insert all your replacements in sequence 
$obj = new myReplace(array('a', 'b')); 

// Lets start the replacement :) 
echo preg_replace_callback(
    "/hi/i", 
    array($obj, 'test'), 
    "Hi mom, hi dad, hi son, hi someone"   
); 
?> 

このコードはになります: お母さん、Bのお父さん、息子は、誰か

関連する問題