Return 字符串,如果它包含特定的单词
Return string if it contains specific word
我有一个字符串。如果字符串具有特定字符,我想在 PHP 中为 return 编写一个脚本。
例如:"Hi, this is the sample.png"是一个字符串。现在我想输出为 "Hi, this is the".
也就是说,如果字符串包含 .jpg、.png,那么我需要从字符串中替换这些词。
这是我的示例代码:
$output = preg_replace('/.png/', '','Hi, this is the sample.png');
print_r($output);exit;
你可以用正则表达式来做到这一点,也许是这样的?
$output = preg_replace('/[^ ]+.png/', '','Hi, this is the sample.png');
$output2 = preg_replace('/[^ ]+.jpg/', '','Hi, this is the sample.jpg');
print_r($output);
print_r($output2);
使用具有特定正则表达式模式的 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, )"
如果您假设其他一些字符是 "crucial words" 的一部分 - 只需将它们添加到字符 class [\w_ <other characters>]
我有一个字符串。如果字符串具有特定字符,我想在 PHP 中为 return 编写一个脚本。
例如:"Hi, this is the sample.png"是一个字符串。现在我想输出为 "Hi, this is the".
也就是说,如果字符串包含 .jpg、.png,那么我需要从字符串中替换这些词。
这是我的示例代码:
$output = preg_replace('/.png/', '','Hi, this is the sample.png');
print_r($output);exit;
你可以用正则表达式来做到这一点,也许是这样的?
$output = preg_replace('/[^ ]+.png/', '','Hi, this is the sample.png');
$output2 = preg_replace('/[^ ]+.jpg/', '','Hi, this is the sample.jpg');
print_r($output);
print_r($output2);
使用具有特定正则表达式模式的 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, )"
如果您假设其他一些字符是 "crucial words" 的一部分 - 只需将它们添加到字符 class [\w_ <other characters>]