Home > Backend Development > PHP Tutorial > 2 ways to remove leading and trailing spaces in php, 2 ways to remove leading and trailing spaces in php_PHP tutorial

2 ways to remove leading and trailing spaces in php, 2 ways to remove leading and trailing spaces in php_PHP tutorial

WBOY
Release: 2016-07-13 10:03:36
Original
953 people have browsed it

Two ways to remove leading and trailing spaces in php, 2 ways of removing leading and trailing spaces in php

It seems to be a very simple problem, but it is actually a bit tricky. First of all, space escaping here, It is not a string and cannot be removed directly using trim().

1, replace
with preg_replace
Copy code 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
Copy code 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/968269.htmlTechArticleTwo ways to remove leading and trailing spaces in php, two ways to remove leading and trailing spaces in php. It seems to be a very simple problem, but in fact It’s still a bit tricky. First of all, the spaces here are escaped, not strings. You can’t remove them directly with trim()...
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