Home > Backend Development > PHP Problem > How to remove spaces on both sides in php

How to remove spaces on both sides in php

醉折花枝作酒筹
Release: 2023-03-10 06:22:02
Original
3206 people have browsed it

Method: 1. Use the mb_ereg_replace function to remove, the syntax format is "mb_ereg_replace(regular expression, '', $str)"; 2. Use the trim function to remove whitespace characters on both sides of the string, the syntax format is is "rtrim(string," ")".

How to remove spaces on both sides in php

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

The first method: through php’s own Function

trim() function removes whitespace characters or other predefined characters on both sides of a string.

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

The second method: replace by regular expression, more powerful
php removes spaces at the beginning and end of the string (including full-width)

<?php
$str="     hello world     "; 
$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

Recommended: " Summary of PHP interview questions in 2021 (collection) 》《php video tutorial

The above is the detailed content of How to remove spaces on both sides in php. 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