I have a string and I need to search and replace such a words that contain only special characters in it. no, any other letter eg( @@#$$ , %^&%%$ , &(){}":?? ).
Function
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.
}
Usage:
echo clean('a|"bc!@£de^&$f g');
I assume that "words" that only contain special characters are chunks of non-whitespace symbols that are not word characters (letters/digits/underscore).
That means you may split the string with whitespaces (with preg_split('~\\s+~', $s)
), get rid of all chunks that only consist of non-word chars (with preg_grep('~^\\W+$~', $arr, PREG_GREP_INVERT)
), and then join the chunks with a space:
$s = "''' Dec 2016, ?!$%^ End '''";
$result = implode(" ", preg_grep('~^\W+$~', preg_split('~\s+~', $s), PREG_GREP_INVERT));
echo $result;
See the PHP demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.