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

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

code link

我假设仅包含特殊字符的 "words" 是非白色 space 符号块,它们不是单词字符 (letters/digits/underscore)。

这意味着你可以用 whitespaces (with preg_split('~\s+~', $s)) 分割字符串,去掉所有只包含非单词字符的块 (with preg_grep('~^\W+$~', $arr, PREG_GREP_INVERT)) ,然后用 space:

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

PHP demo