如果包含特定单词,则返回字符串


Return string if it contains specific word

我有一个字符串。我想用PHP写一个脚本,如果字符串有特定字符,就返回一个字符串。

例如:"嗨,这是示例.png"是一个字符串。现在我想输出为"嗨,这是"。

也就是说,如果字符串包含.jpg、.png,那么我需要替换字符串中的这些单词。

这是我的示例代码:

$output = preg_replace('/.png/', '$1','Hi, this is the sample.png');
print_r($output);exit;

使用具有特定正则表达式模式的preg_replace函数的解决方案:

$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>]

中即可

您可以用正则表达式来实现这一点,也许是这样的?

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