删除包含非字母数字字符的字符串中的“单词”?

时间:2016-06-25 03:34:26

标签: php regex nlp

PHP中推荐使用非字母数字字符删除字符串中'words'的方法是什么?

$string = "Test let's test 123. https://youtu.be/dQw4w9WgXcQ EOTest.";

期望的结果:

"Test test 123. EOTest.";

方法1 - 正则表达式 方法2 - explode(),foreach()和str_replace或preg_replace

1 个答案:

答案 0 :(得分:1)

尝试使用preg_splitpreg_grepimplode函数,如下所示:

$string = "Test let's test 123. https://youtu.be/dQw4w9WgXcQ EOTest.";
$words = preg_split('/\s+/', $string); // split on one or more spaces
$filter = preg_grep('/^[A-Za-z\d.]+$/', $words); // allow dot, letters, and numbers
$result = implode(' ', $filter); // turn it into a string
print_r($result); // -> Test test 123. EOTest.

我希望有所帮助!

相关问题