3

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! ;)

2
  • 1
    So which output are you expecting for the string above? Commented Oct 22, 2013 at 10:28
  • If it's possible, an array like I wrote. (Thank you for editing my post :$) Commented Oct 22, 2013 at 10:34

2 Answers 2

2

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] => 
        )

)
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome! I didn't knew this web site! I just changed to: (\d+)|([\WA-Za-z]+) to use spaces. Thank you!
I come back ^^ It's strange, I have the letters but not the numbers... An idea ? But if I test here: rubular.com/r/X0RRECjww5, it works...
As you can see there, the numbers are all in index 1 of $match, while the letters are in index 2 of $match. Make sure you get the right index. Also, what do you use for input? A single, long string?
It's a normal string. I checked my input string and I have something like: Abc aaa25. Then, I check my arrays: count(numbers) and count(letters). One of them are 0 => numbers. I don't understand :/
Use preg_match_all instead of preg_match, see updated answer
0

Maybe something like this?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.