百科狗-知识改变命运!
--

substr() - 返回字符串的子串 - php 字符串函数

乐乐1年前 (2023-11-21)阅读数 10#技术干货
文章标签字符串

substr()

(PHP 4, PHP 5, PHP 7)

返回字符串的子串

说明

substr(string $string, int $start[,int $length] ): string

substr() - 返回字符串的子串 - php 字符串函数

返回字符串$string由$start和$length参数指定的子字符串。

参数

$string

输入字符串。必须至少有一个字符。

$start

如果$start是非负数,返回的字符串将从$string的$start位置开始,从 0 开始计算。例如,在字符串“abcdef”中,在位置0的字符是“a”,位置2的字符串是“c”等等。

如果$start是负数,返回的字符串将从$string结尾处向前数第$start个字符开始。

如果$string的长度小于$start,将返回FALSE

使用负数$start

$length

如果提供了正数的$length,返回的字符串将从$start处开始最多包括$length个字符(取决于$string的长度)。

如果提供了负数的$length,那么$string末尾处的$length个字符将会被省略(若$start是负数则从字符串尾部算起)。如果$start不在这段文本中,那么将返回FALSE

如果提供了值为0FALSENULL的$length,那么将返回一个空字符串。

如果没有提供$length,返回的子字符串将从$start位置开始直到字符串结尾。

使用负数$length

返回值

返回提取的子字符串,或者在失败时返回FALSE

更新日志

版本说明
7.0.0如果$string的字符串长度与$start相同时将返回一个空字符串。在之前的版本中,这种情况将返回FALSE
5.2.2 - 5.2.6If the$startparameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.

范例

Example #3substr()基本用法

Example #4substr()casting behaviour

Output of the above example in PHP 7:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Output of the above example in PHP 5:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

错误/异常

错误时返回FALSE

参见

  • strrchr()查找指定字符在字符串中的最后一次出现
  • substr_replace()替换字符串的子串
  • preg_match()执行匹配正则表达式
  • trim()去除字符串首尾处的空白字符(或者其他字符)
  • mb_substr()获取部分字符串
  • wordwrap()打断字符串为指定数量的字串
  • 字符串访问和修改
For getting a substring of UTF-8 characters, I highly recommend mb_substr
may be by following functions will be easier to extract the needed sub parts from a string:

here comes the source:
Just a little function to cut a string by the wanted amount. Works in both directions.

Enjoy ;)
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers. 
For example when using ip2country, or eliminating same range of ip addresses from your website :D
If you want to have a string BETWEEN two strings, just use this function:
Coming to PHP from classic ASP I am used to the Left() and Right() functions built into ASP so I did a quick PHPversion. hope these help someone else making the switch
function left($str, $length) {
  return substr($str, 0, $length);
}
function right($str, $length) {
  return substr($str, -$length);
}
I created some functions for entity-safe splitting+lengthcounting:
You might expect substr('123456', 6) to return an empty string. Instead it returns boolean FALSE.
This behavior should be mentioned in the Return Values section of the manual. Instead it is only mentioned in the Parameters section.
If you need an empty string instead of a boolean FALSE you should typecast the result to a string.
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:
(substr) 3.24
(direct access) 11.49
(strstr) 4.96
(With standard deviations 0.01, 0.02 and 0.04)
THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
[English]
I created python similar accesing list or string with php substr & strrev functions.
Use: str($string,$pattern)
About the python pattern,
http://docs.python.org/release/1.5.1p1/tut/strings.html
http://effbot.org/zone/python-list.htm
About of pattern structures
[start:stop:step]
Example,

Output,
thetoacn
eht
aom
htan
This is function phpfiddle link: http://phpfiddle.org/main/code/e82-y5d
or source;

Good works..
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string. The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.
The output from the examples:
c
cd
cdefg
abcd
abcd
efg
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.

curly braces syntax is faster and more readable IMHO..
Shortcuts :
Getting the first character of a string
substr($string, 1)
Getting the last character of a string
substr($string, -1)
Remove the first character of a string
substr($string,1)
Remove the last character of a string
substr($string, 0, -1)
Be aware of a slight inconsistency between substr and mb_substr
mb_substr("", 4);   returns empty string
substr("", 4);       returns boolean false
tested in PHP 7.1.11 (Fedora 26) and PHP 5.4.16 (CentOS 7.4)
I have developed a function with a similar outcome to jay's
Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is... it chops off anything after and including the last space.
Truncate a float number. Similar to the Excel trunc function.
Regarding the utf8_substr function from lmak: The pattern '/./u' doesn't match newline characters. This means that the substring from 0 to the total length of the string will miss the number of characters in the end matching the number of newlines in the string. To fix this one can add the s modifier (PCRE_DOTALL) in the pattern:
Using a 0 as the last parameter for substr().
As per examples

works no problem. However 

will get you nothing. Just a quick heads up
When using a value of a wrong type as second parameter , substr() does not return FALSE but NULL although the docs say, it should return FALSE on error.
Prior to PHP 5.3, substr() tries to cast the second parameter to int and doesn't throw any errors. Since PHP 5.3 a warning is thrown.
If you need to parse utf-8 strings char by char, try this one:

- it works without mb_substr
- it is fast, because it grabs characters based on indexes when possible and avoids any count and split functions
I needed a function like lpad from oracle, or right from SQL
 then I use this code :

Result: 
 4152
------------------------------------------------
This function is really simple, I just wanted to share, maybe helps someone out there. 
regards,
Shortens the filename and its expansion has seen.
Drop extensions of a file (even from a file location string)

output: c:/some dir/abc defg. hi
Hope it may help somebody like me.. (^_^)
And as always there is bound to be a bug:
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() ...
Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen() get it... 
Enjoy it :) ...
--- Bleakwind
QQ:940641
http://www.weaverdream.com
PS:I'm sorry my english is too poor... :( 

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)