PHP quickly implements deletion of special characters such as spaces, tabs, newlines, etc. (two methods)

藏色散人
Release: 2023-03-12 07:20:01
Original
3663 people have browsed it

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(&#39;/[\x00-\x1F\x7F]/&#39;, &#39;&#39;, $str);

// 显示修改字符串
echo($str);
Copy after login

Output result:

ILOVEPHP
Copy after login
Copy after login

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(&#39;/[[:cntrl:]]/&#39;, &#39;&#39;, $str);

// 显示修改字符串
echo($str);
Copy after login

Output result:

ILOVEPHP
Copy after login
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template