PHP:从字符串末尾获得第n个字符
我确定必须有一个简单的方法才能从字符串末尾获得第n个字符。PHP:从字符串末尾获得第n个字符
例如:
$NthChar = get_nth('Hello', 3); // will result in $NthChar='e'
<?php
function get_nth($string, $offset) {
$string = strrev($string); //reverse the string
return $string[$offset];
}
$string = 'Hello';
echo get_nth($string, 3);
至于$字符串[3]会给你3号线的偏移,但你希望它向后,你需要串扭转它。
编辑:
尽管其他的答案(矿后贴)使用子串,并且它可以是一个一个衬里,它是几乎不可读有substr($string, -2, 1)
,那么就反转串和输出所述偏移。
嗯,也许谁downvoted会告诉我们为什么:) –
我reall你没有想法。然而,我的** + 1 **给你。 –
@RoyalBg对于回复2yo评论感到抱歉。 _内部,PHP字符串是字节数组。因此,使用数组括号访问或修改字符串的方式是**不是多字节安全**,并且只能使用单字节编码的字符串完成,例如ISO-8859-1._ 在[手册]中提到(https://secure.php.net/manual/en/language.types.string.php) – bangbambang
substr($string, -3);//returns 3rd char from the end of the string
'$ string ='Hello'; echo substr($ string,-3);'returns'llo' –
将给你输入为llo的输出为你好 –
像这样:
function get_nth($string, $index) {
return substr($string, strlen($string) - $index - 1, 1);
}
这里是一个不错的功能,你可以使用同样的,你的情况http://www.junnfo.com/extract -nth-character-from-astring-php.html –
你真的认为它是你想要的第n个字符还是第(n + 1)个(直到你数0,第1 ....方法) –