方法:1、使用mb_ereg_replace函数去除,语法格式为“mb_ereg_replace(正则表达式, '', $str)”;2、使用trim函数移除字符串两侧的空白字符,语法格式为“rtrim(字符串,“ ”)”。

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑
第一种方法:通过php自带的函数
trim() 函数移除字符串两侧的空白字符或其他预定义字符。
<?php $str = "Hello World!"; echo $str . "<br>"; echo trim($str,"Hed!"); ?>
第二种方法:通过正则表达式替换,功能更强
php去除字符串首尾空格(包括全角)
立即学习“PHP免费学习笔记(深入)”;
<?php
$str=" hello world ";
$str = mb_ereg_replace('^( | )+', '', $str);
$str = mb_ereg_replace('( | )+$', '', $str);
echo mb_ereg_replace(' ', "\n ", $str);
?>推荐:《2021年PHP面试题大汇总(收藏)》《php视频教程》
以上就是php如何去掉两边空格的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号