php删除左端与右端空格的方法,php删除左端空格
本文实例讲述了php删除左端与右端空格的方法。分享给大家供大家参考。具体方法如下:
在php中删除函数比js要具体很多,除了trim()函数,还有ltrim()和rtrim()函数,他们分别要删除前后左右的空格了,除了这三个函数还可以使用正则删除.
ltrim()函数:ltrim($str, $charlist)
$str表示被处理的字符串,$charlist是要删除的特殊字符,若为空则去除左端的空格,代码如下:
复制代码 代码如下:
$t=" ...I'm Jacky...";
echo "a" .$t ."
";
$left=ltrim($t);
echo "a" .$left ."
";
$lleft=ltrim($left,".");
echo $lleft;
?>
rtrim()函数:rtrim($str, $charlist)
$str表示被处理的字符串,$charlist是要删除的特殊字符,若为空则去除右端的空格,代码如下:
复制代码 代码如下:
$a="htm ";
echo $a ."l" ."
";
echo rtrim($a) ."l";
?>
trim()函数,首先去掉头尾空格,代码如下:
复制代码 代码如下:
$str = " This line containstliberal rn use of whitespace.nn";
// 首先去掉头尾空格
$str = trim($str);
// 接着去掉两个空格以上的
$str = preg_replace('/s(?=s)/', '', $str);
// 最后将非空格替换为一个空格
$str = preg_replace('/[nrt]/', ' ', $str);
使用上面的例子可以去掉所有多余的空格,首先使用TRim()去头尾空格,接着用preg_replace()去掉重复的空格.
通过正则表达式替换,功能更强,php去除字符串首尾空格(包括全角),代码如下:
复制代码 代码如下:
$str=" 帮客之家 www.jb51.net ";
$str = mb_ereg_replace('^( | )+', '', $str);
$str = mb_ereg_replace('( | )+$', '', $str);
echo mb_ereg_replace(' ', "n ", $str);
?>
希望本文所述对大家的PHP程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
