Is there any equivalent function that returns the character at position X
in PHP?
I went through the documentation but couldn't find any. I am looking for something like:
$charAtPosition20 = strCharAt(20, $myString);
The accepted answer works well for single-byte (ASCII) strings, but it breaks for multibyte (Unicode) strings. For these, you need to use mb_
functions – just make sure you have the mbstring extension installed and enabled.
To get character at position of a multibyte string:
$char = mb_substr($string, $position, 1);
mb_substr
is just like substr
but for multibyte strings, so the 1
at the end returns only 1 character, but if you want more characters, you can change this accordingly.
You can use: $myString[20]
There are two ways you can achieve this:
Use square brackets and an index to directly access the character at the specified location, like: $string[$index]
or $string[1]
;
Use the substr
function: string substr ( string $string , int $start [, int $length ] )
See http://us2.php.net/manual/en/function.substr.php for further informations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With