Lapinou
Lapinou

Reputation: 1477

Regexp PHP Split number and string

I would like to split a string contains some numbers and letters. Like this:

ABCd Abhe123
123ABCd Abhe
ABCd Abhe 123
123 ABCd Abhe

I tried this:

<?php preg_split('#(?<=\d)(?=[a-z])#i', "ABCd Abhe 123"); ?>

But it doesn't work. Only one cell in array with "ABCd Abhe 123"
I would like for example, in cell 0: numbers and in cell1: string:

[0] => "123",
[1] => "ABCd Abhe"

Thank you for your help! ;)

Upvotes: 3

Views: 237

Answers (2)

Richard de Wit
Richard de Wit

Reputation: 7452

Use preg_match_all instead

preg_match_all("/(\d+)*\s?([A-Za-z]+)*/", "ABCd Abhe 123" $match);

For every match:

  • $match[i][0] contains the matched segment
  • $match[i][1] contains numbers
  • $match[i][2] contains letters

(See here for regex test)

Then put them in an array

for($i = 0; $i < count($match); $i++)
{
    if($match[i][1] != "")
        $numbers[] = $match[1];

    if($match[i][2] != "")
        $letters[] = $match[2];
}

EDIT1

I've updated the regex. It now looks for either numbers or letters, with or without a whitespace.


EDIT2

The regex is correct, but the arrayhandling wasn't. Use preg_match_all, then $match is an array containing arrays, like:

Array
(
    [0] => Array
        (
            [0] => Abc
            [1] =>  aaa
            [2] => 25
        )

    [1] => Array
        (
            [0] => 
            [1] => 
            [2] => 25
        )

    [2] => Array
        (
            [0] => Abc
            [1] => aaa
            [2] => 
        )

)

Upvotes: 2

Lajos Veres
Lajos Veres

Reputation: 13725

Maybe something like this?

$numbers = preg_replace('/[^\d]/', '', $input);
$letters = preg_replace('/\d/', '', $input);

Upvotes: 0

Related Questions