2016-08-01 10 views
-3

文字列があります。私は特定の文字を持っている場合は、文字列を返すPHPのスクリプトを書いてみたい。特定の単語が含まれている場合は文字列を返します

たとえば、「こんにちは、これはsample.pngです」という文字列です。今私は "こんにちは、これは"と出力したいと思います。

たとえば、文字列に.jpg、.pngが含まれている場合、それらの単語を文字列から置き換える必要があります。

これは私のサンプルコードです:

+0

何を試しましたか?いくつかのコードを表示してください。 –

答えて

1

ソリューション:あなたは「決定的な言葉」の一部であることを他のいくつかの文字を仮定した場合

$str = 'Hi, this is the sample_test.png (or, perhaps, sample_test.jpg)'; 
$output = preg_replace('/\b[\w_]+\.(png|jpg)\b/', '', $str); 

print_r($output); // "Hi, this is the (or, perhaps,)" 

は - ちょうど文字クラス[\w_ <other characters>]にそれらを追加します

+0

文字列にsample_test.pngが含まれている場合、コードはtest.pngだけを置き換えます。私はsample_test.pngを置き換えたい – Guru

+0

@Guru、ok、私の更新を参照してください – RomanPerekhrest

+0

ありがとう@Roman – Guru

1

あなたはおそらく、正規表現でこのような何かをこれを行うことができますか?特定の正規表現パターンでpreg_replace機能を使用して

$output = preg_replace('/[^ ]+.png/', '$1','Hi, this is the sample.png'); 
$output2 = preg_replace('/[^ ]+.jpg/', '$1','Hi, this is the sample.jpg'); 
print_r($output); 
print_r($output2); 
関連する問題