Method: 1. Use "str_replace("specified symbol","",$str)" to remove the specified symbol; 2. Use "preg_match_all("/[\x{4e00}-\x{9fa5} a-zA-Z0-9]/u","$str",$result);"Filter out all symbols.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php removes strings Symbols in
Method 1: Use the str_replace() function--remove specified symbols
The str_replace() function can search for symbols in the string Specify the symbol and replace it with the empty character
For example: remove the ? symbol
<?php header("Content-type:text/html;charset=utf-8"); $str = "php.cn?php中文网。zblog,?#$%^&())*(&^"; $newstr=str_replace("?","",$str); echo $newstr; ?>
Method 2: Use preg_match_all() Function
preg_match_all() function can be used with regular expressions to filter strings, retaining only Chinese, English and numbers, and removing all other symbols
<?php header("Content-type:text/html;charset=utf-8"); $str = "php.cn?php中文网。zblog,?#$%^&())*(&^"; preg_match_all("/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u","$str",$result); var_dump($result); ?>
preg_match_all() function accepts a third parameter of array type to store all matching results.
You can use the join() function to splice the result array into a string
echo join('',$result[0]);
PHP Video Tutorial"
The above is the detailed content of How to remove symbols from string in php. For more information, please follow other related articles on the PHP Chinese website!