简体   繁体   中英

PHP: Get nth character from end of string

I'm sure there must be an easy way to get nth character from the end of string.

For example:

$NthChar = get_nth('Hello', 3); // will result in $NthChar='e'

就这样做吧

  $rest = substr("abcdef", -3, 1); // returns 'd'

Like this:

function get_nth($string, $index) {
    return substr($string, strlen($string) - $index - 1, 1);
}
<?php
function get_nth($string, $offset) {
    $string = strrev($string); //reverse the string
    return $string[$offset];
}

$string = 'Hello';
echo get_nth($string, 3);

As $string[3] will give you the 3rd offset of the string, but you want it backwards, you need to string reverse it.


Edit:

Despite other answers (posted after mine) are using substring, and it can be a one liner, it is hardly readable to have substr($string, -2, 1) , then just reverse the string and output the offset.

substr($string, -3);//returns 3rd char from the end of the string

from substr examples

// Accessing single characters in a string
// can also be achieved using "square brackets"

thus:

$str = "isogram";
echo $str[-1]; // m
echo $str[-2]; // a
echo $str[-3]; // r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM