Home > php教程 > php手册 > PHP中去掉字符串首尾空格的方法

PHP中去掉字符串首尾空格的方法

WBOY
Release: 2016-06-06 20:40:45
Original
1881 people have browsed it

今天在做php的时候需要将字符串首尾的空格去掉,百度一下发现php就自带这个函数trim,果然方便多了,特分享下

第一种方法:通过php自带的函数
/*
trim 去除一个字符串两端空格,
rtrim 是去除一个字符串右部空格,
ltrim 是去除一个字符串左部空格。

*/
?>
echo trim(" 空格 ")."
";
echo rtrim(" 空格 ")."
";
echo ltrim(" 空格 ")."
";
?>
第二种方法:通过正则表达式替换,功能更强
php去除字符串首尾空格(包括全角)
代码如下:

$str="     脚本之家 www.jb51.net     ";
$str = mb_ereg_replace('^( | )+', '', $str);
$str = mb_ereg_replace('( | )+$', '', $str);
echo mb_ereg_replace('  ', "\n  ", $str);
?>
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template