The previous article "PHP Mathematical Function Practice 4: Rounding Floating Point Numbers from Zero to Specified Decimal Places" introduces how to round floating point numbers from zero to specified decimal places. Number, interested friends can learn about it ~
Then this article will introduce to you how to solve a very common problem in the usual development process, which is how to delete special characters from a string!
The special characters involved in this article include: space ("\0
"), horizontal tab character ("\t
"), newline character (" \n
") , vertical tab ("\v
") and ESC ("\e
").
Below we will use two different methods to remove special characters from PHP strings:
First method:
Use universal regular expressions Expressions: There are many regular expressions that can be used to remove all characters with an ASCII value below 32. Here, we will use the preg_replace() method.
Note: The ereg_replace() method has been removed from PHP >= 7, so here we will use the preg_replace() method.
php code is as follows:
<?php $str = "\eI\t\tLOVE\v\vPHP\n"; //使用preg_replace方法删除所有特殊字符串 $str = preg_replace('/[\x00-\x1F\x7F]/', '', $str); // 显示修改字符串 echo($str);
Output result:
ILOVEPHP
Second method:
Use the "cntrl" regular expression: this can also be used to remove all special characters. And [:cntrl:] represents all special characters.
PHP code is as follows:
<?php $str = "\eI\t\tLOVE\vPHP\n"; //使用preg_replace方法删除所有特殊字符串 $str = preg_replace('/[[:cntrl:]]/', '', $str); // 显示修改字符串 echo($str);
Output result:
ILOVEPHP
Note:
preg_replace
function is used to execute a Regular expression search and replace.
The syntax: mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Instructions: Search for the part of the subject that matches pattern and replace it with replacement.
PHP Chinese website platform has a lot of video teaching resources. Welcome everyone to learn "PHP Video Tutorial"!
The above is the detailed content of PHP quickly implements deletion of special characters such as spaces, tabs, newlines, etc. (two methods). For more information, please follow other related articles on the PHP Chinese website!