2 ways to remove leading and trailing spaces in PHP_PHP Tutorial

WBOY
Release: 2016-07-13 10:03:27
Original
741 people have browsed it

Two ways to remove leading and trailing spaces in PHP

This article mainly introduces two ways to remove leading and trailing spaces in PHP. This article gives the preg_replace substitution and trim functions. Two methods and examples are given. Friends in need can refer to it

This seems to be a very simple problem, but it is actually a bit tricky. First of all, the spaces are escaped here, not strings, and cannot be removed directly using trim().

1, replace

with preg_replace

The code is as follows:


$test = " dfadad On the relationship between the responsible people and the three British 775fd ";
$test = preg_replace('/^( |s)*|( |s)*$/', '', $test);
var_dump($test);

//The results are as follows:

string 'dfadad On the relationship between the responsible people and the three British 775fd' (length=35)


This method was provided by friends in the group, and I would like to express my gratitude. This method is recommended because it is universal

2, trim method

The code is as follows:


$test = " dfadad 3333adf775fd ";
$test = trim(html_entity_decode($test),chr(0xc2).chr(0xa0));
var_dump($test);

//The results are as follows:

string 'dfadad 3333adf775fd' (length=19)


This method is found in the official manual of PHP. If it is UTF8 encoding, there is no problem in using this method. If GBK, GB2312, garbled characters will appear. There is also json_encode. If this function is gbk or gb2312, Chinese characters will be replaced by null. It is recommended to use utf8 encoding.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/968658.htmlTechArticle2 ways to remove leading and trailing spaces in php. This article mainly introduces 2 ways to remove leading and trailing spaces in php. ,This article gives two methods of using preg_replace substitution and trim function and gives examples. Required...
Related labels:
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