经常看到有新手问PHP有没有类似asp的left函数或right函数,实现截取某字符串左边或右边开始N个字符的函数。答案当然是有的。
PHP中的substr函数就可以做的到,只不过PHP把二个函数合二为一了。
现在整理了一下substr函数的用法,做了几个例子以解新人之惑,高手请飘过。
我们先来看一下PHP substr函数的语法:
string substr(string string, int start, int [length])
参数string为要操作的字符串
参数start为你要截取的字符串的开始位置,若start为负数时,则表示从倒数第start开始截取length个字符
可选参数length为你要截取的字符串长度,若在使用时不指定则默认取到字符串结尾。若length为负数时,则表示从start开始向右截取到末尾倒数第length个字符的位置
起初用这个函数时可能感觉到别扭,不过你要是把PHP substr函数的语法搞懂了,那他的功能比asp中的left和right,有过之无不及,非常好用。下面我们举例来看他的用法:
1、从第4个字符开始截取到字符串末尾,类似asp中的left:
<?php $str = "www.icoa.cn"; echo substr($str,4); ?>
输出: icoa.cn
2、PHP substr函数从右边截取3个字符,类似asp中的right:
<?php $str = "www.icoa.cn"; echo substr($str,-3); ?>
输出:.cn
3、PHP substr函数从第4个字符开始截取3个字符:
<?php $str = "www.icoa.cn"; echo substr($str,4,3); ?>
输出:ico
4、有时我们知道一个字符串的开始和结尾,中间是不定长的字符,这时除了用PHP substr函数的正则外我们还可以用substr实现(当然要得到中间的字符方法有N种,在此只是举例substr的应用):
本例去掉开头4个字符和结尾3个字符,输出中间的字符串:
<?php $str = "www.icoa.cn"; echo substr($str,4,-3); ?>
输出:icoa
【相关教程推荐】
2. php从入门到精通
3. bootstrap教程

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

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
