2016-08-01 87 views
-3

我有一个字符串。我想在PHP中编写一个脚本,以便返回一个字符串,如果它有特定的字符。返回字符串,如果它包含特定的字

例如:“嗨,这是sample.png”是一个字符串。现在我想输出为“嗨,这就是”。

即,如果字符串包含.jpg,.png,那么我需要从字符串中替换这些单词。

这是我的示例代码:

+0

你试过了什么?请显示一些代码。 –

回答

1

使用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>]

+0

如果字符串包含sample_test.png,那么你的代码只替换test.png。但我想替换sample_test.png – Guru

+0

@Guru,好的,看我的更新 – RomanPerekhrest

+0

谢谢@Roman – Guru

1

你可以用正则表达式,也许像这样做呢?

$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); 
相关问题