Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any equivalent function that returns the character at position `X` in PHP?

Tags:

string

php

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);
like image 747
fmsf Avatar asked Jul 14 '09 23:07

fmsf


3 Answers

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.

like image 156
Sumit Avatar answered Sep 29 '22 06:09

Sumit


You can use: $myString[20]

like image 29
Michael Morton Avatar answered Sep 29 '22 07:09

Michael Morton


There are two ways you can achieve this:

  1. Use square brackets and an index to directly access the character at the specified location, like: $string[$index] or $string[1];

  2. 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.

like image 24
mkamthan Avatar answered Sep 29 '22 08:09

mkamthan