I have a variable $var = "My name's Ankit"
. I want to store all the English alphabet characters of $var
into an array $charvar
. I know that I can use a simple for loop over the entire length of $var
and array_push
the characters if they are English characters else ignore. However, I wanted to know if PHP provides some function which can do this.
What I want in $charvar
is:
Array
(
[0] => M
[1] => y
[2] => n
[3] => a
[4] => m
[5] => e
[6] => s
[7] => A
[8] => n
[9] => k
[10] => i
[11] => t
)
The other answers are not good enough.
This does EXACTLY what you want in one step / one function. Split the string on zero or more non-alphabetical characters.
Code (Demo):
$var = "My name's Ankit";
$charvar = preg_split('/[^a-z]*/i', $var, 0, PREG_SPLIT_NO_EMPTY);
var_export($charvar);
Output: (no subarrays)
array (
0 => 'M',
1 => 'y',
2 => 'n',
3 => 'a',
4 => 'm',
5 => 'e',
6 => 's',
7 => 'A',
8 => 'n',
9 => 'k',
10 => 'i',
11 => 't',
)