Domanda

i know that this is a beginner level question, but i am stuck here and i need help.

i want to store each alphabet in an array. (Only Alphabets not integers)

let me show you the previous code that i am using

$str = "ab c45 d123ef";
preg_match_all('/./us', $str, $ar);
echo '<pre>';
print_r($ar);

its output

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] =>  
            [3] => c
            [4] => 4
            [5] => 5
            [6] =>  
            [7] => d
            [8] => 1
            [9] => 2
            [10] => 3
            [11] => e
            [12] => f
        )

)

But it also separate integers... what i have to change in the preg_match expression, i want this output.

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] =>  
            [3] => c
            [4] => 45
            [5] =>  
            [6] => d
            [7] => 123
            [8] => e
            [9] => f
        )

)
È stato utile?

Soluzione

preg_match_all('/[\d.]+|./us', $str, $ar);

[\d.] matches a digit or decimal point, the + quantifier after it matches a sequence of them.

Result:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] =>  
            [3] => c
            [4] => 45
            [5] =>  
            [6] => d
            [7] => 123
            [8] => e
            [9] => f
        )

)

Altri suggerimenti

A way with preg_split:

$result = preg_split('/(?=\pL)|(?<=\pL)/', $str, -1, PREG_SPLIT_NO_EMPTY);

You obtain:

Array
(
    [0] => a
    [1] => b
    [2] =>  
    [3] => c
    [4] => 45 
    [5] => d
    [6] => 123
    [7] => e
    [8] => f
)

The current pattern matches two kind of positions, positions followed by a letter (?=\pL), and positions preceded by a letter (?<=\pL).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top