How to remove spaces on both sides of a string in php?

青灯夜游
Release: 2023-03-07 06:28:02
Original
4536 people have browsed it

php method to remove spaces on both sides of a string: 1. Directly use the trim() function to remove spaces at both ends of a string; 2. Use rtrim() and ltrim() to remove the right and left sides of a string respectively. Spaces; 3. Use the mb_ereg_replace() function with regular expressions to replace and remove spaces.

How to remove spaces on both sides of a string in php?

Recommended: "PHP Video Tutorial"

php removes spaces on both sides of the string

The first method: through the function that comes with php

<?php
/*
trim 去除一个字符串两端空格,
rtrim 是去除一个字符串右部空格,
ltrim 是去除一个字符串左部空格。
*/

$str = " Hello World! ";
echo trim($str)."<br>";
echo rtrim($str)."<br>";
echo ltrim($str)."<br>";
?>
Copy after login

The second method: through regular expression Formula replacement, more powerful

php removes spaces at the beginning and end of the string (including full-width)

<? 
$str="     PHP中文网 www.php.cn     "; 
$str = mb_ereg_replace(&#39;^( | )+&#39;, &#39;&#39;, $str); 
$str = mb_ereg_replace(&#39;( | )+$&#39;, &#39;&#39;, $str); 
echo mb_ereg_replace(&#39;  &#39;, "\n  ", $str); 
?>
Copy after login

Related recommendations: php training

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

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