如何获取 PHP 字符串的最后 7 个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10542310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the last 7 characters of a PHP string?
提问by Dave
How would I go about grabbing the last 7 characters of the string below?
我将如何抓取下面字符串的最后 7 个字符?
For example:
例如:
$dynamicstring = "2490slkj409slk5409els";
$newstring = some_function($dynamicstring);
echo "The new string is: " . $newstring;
Which would display:
哪个会显示:
The new string is: 5409els
回答by Asaph
Use substr()with a negative number for the 2nd argument.
使用substr()负数作为第二个参数。
$newstring = substr($dynamicstring, -7);
From the php docs:
从php 文档:
string substr ( string $string , int $start [, int $length ] )If start is negative, the returned string will start at the start'th character from the end of string.
string substr ( string $string , int $start [, int $length ] )如果 start 为负,则返回的字符串将从字符串末尾的第 start 个字符开始。
回答by Vitaly Muminov
umh.. like that?
嗯..像那样?
$newstring = substr($dynamicstring, -7);
回答by MERT DO?AN
Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:
使用多字节字符代码更安全的结果,总是使用 mb_substr 而不是 substr。utf-8 示例:
$str = 'Ne zaman seni dü?ünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
mb_substr( $str, -7, null, 'UTF-8') ;
回答by Abdul Manan
It would be better to have a check before getting the string.
在获取字符串之前进行检查会更好。
$newstring = substr($dynamicstring, -7);
if characters are greater then 7 return last 7 characters else return the provided string.
如果字符大于 7,则返回最后 7 个字符,否则返回提供的字符串。
or do this if you need to return message or error if length is less then 7
或者如果您需要返回消息或如果长度小于 7 的错误,请执行此操作
$newstring = (strlen($dynamicstring)>7)?substr($dynamicstring, -7):"message";
回答by mariovials
For simplicity, if you do not want send a message, try this
为简单起见,如果你不想发送消息,试试这个
$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );
回答by developper
for last 7 characters
最后 7 个字符
$newstring = substr($dynamicstring, -7);
$newstring : 5409els
$newstring : 5409els
for first 7 characters
前 7 个字符
$newstring = substr($dynamicstring, 0, 7);
$newstring : 2490slk
$newstring : 2490slk
回答by keerthi
last 7 characters of a string:
字符串的最后 7 个字符:
$rest = substr( "abcdefghijklmnop", -7); // returns "jklmnop"
$rest = substr("abcdefghijklmnop", -7); // 返回 "jklmnop"

