繁体   English   中英

如何使用正则表达式替换字符串中仅包含特殊字符的单词

[英]how to replace word that contains only special characters from string using regular expression

我有一个字符串,我需要搜索并替换其中只包含特殊字符的单词。 不,任何其他字母,例如(@@#$$,%^&%% $,&(){}“:??)。

功能

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

用法:

echo clean('a|"bc!@£de^&$f g');

代码链接

我假设只包含特殊字符的“单词”是非空白符号的块,而不是单词字符(字母/数字/下划线)。

这意味着你可以用空格分割字符串(使用preg_split('~\\s+~', $s) ),去除所有仅包含非字符字符的块(使用preg_grep('~^\\W+$~', $arr, PREG_GREP_INVERT) ),然后用空格加入块:

$s = "''' Dec 2016, ?!$%^ End '''";
$result = implode(" ", preg_grep('~^\W+$~', preg_split('~\s+~', $s), PREG_GREP_INVERT));
echo $result;

请参阅PHP演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM