Home >Backend Development >PHP Problem >How to remove spaces from variables in php

How to remove spaces from variables in php

藏色散人
藏色散人Original
2021-09-15 09:09:001728browse

How to remove spaces in variables in php: 1. Delete spaces in strings through trim method; 2. Replace spaces with preg_replace method; 3. Replace spaces with str_replace function.

How to remove spaces from variables in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to remove variable spaces in php?

php remove spaces from string

##1, Commonly used methods trim
Example:

$test = " abc";
//方法一:函数把 HTML 实体转换为字符。
$converted = html_entity_decode($test),chr(0xc2).chr(0xa0);  
//方法二:
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES))); 
//php:45:string ' abc' (length=5) 
$converted = trim($converted,chr(0xC2).chr(0xA0)); 
// should work
var_dump($converted);
Hexadecimal conversion: 0xC2 to  0xA0 to space

The official chr(0xC2).chr(0xA0) is not very If you understand what it means, friends who know can leave a message below

2, use preg_replace to replace
Example:

$str = ' t e  s t';
$str = preg_replace('/\s+/', '', $str);
// 将会改变为'test'

3, use str_replace to replace
Example

$str = " t e  s t";
$str=str_replace(" ",'',$str);
echo $str

Recommended study: "

PHP Video Tutorial"

The above is the detailed content of How to remove spaces from variables in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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