2017-02-20 3 views
0

をチェックするのは、私は次のコードがあるとしましょう:PHP str_replace;交換するよりも多くの部分

$string = "Hello! This is a test. Hello this is a test!" 

echo str_replace("Hello", "Bye", $string); 

これはBye$string内のすべてのHelloに置き換えられます。どのようにすればいいですか? Helloの後に!のすべての部分を除外します。

手段は、私はこの出力をしたい:Hello! This is a test. Bye this is a test!

はそれを行うにはPHPの方法はありますか?

答えて

2

あなたは正規表現をする必要があります:

echo preg_replace("/Hello([^!])/", "Bye$1", $string); 

[]は文字クラスであると^は、NOTを意味します。だからHelloの後には!が続きます。 ()にはHelloの後にある!が含まれているので、交換で$1(最初のキャプチャグループ)として使用できます。

2

特定の正規表現パターンでpreg_repalce機能を使用してソリューション:

$string = "Hello! This is a test. Hello this is a test!"; 
$result = preg_replace("/Hello(?!\!)/", "Bye", $string); 

print_r($result); 

出力:

Hello! This is a test. Bye this is a test! 

(?!\!) - 先読み負の主張は、それは続いていない場合にのみ、Hello単語と一致します '!'

関連する問題