Mackintoast
Mackintoast

Reputation: 1437

splitting name and id

I have a string

"JonSmith02-11-1955"

I use preg_split to get JonSmith (reg='[0-9-]') then do it again ('[a-zA-Z]\ ') to get his birthdate. Is there any better way to get them both in one split ?

Upvotes: 3

Views: 76

Answers (5)

Patrick Desjardins
Patrick Desjardins

Reputation: 140833

^([a-zA-z]*)([0-9]*)\-(.+)*$

For this example :

JonSmith02-11-1955

Give :

JonSmith
02
11-1955

enter image description here

Upvotes: 1

phatskat
phatskat

Reputation: 1815

Try /(\w*)(\d{2}-\d{2}-\d{4})/ as your regex - someone else can probably do that more efficiently. This will give you two capturing groups, so

$array = preg_match_all('/(\w*)(\d{2}-\d{2}-\d{4})/', "JonSmith02-11-1955");
print_r($array); 
/*
Array
(
    [0] => Array
        (
            [0] => JonSmith02-11-1955
        )

    [1] => Array
        (
            [0] => JonSmith
        )

    [2] => Array
        (
            [0] => 02-11-1955
        )

)

*/

Upvotes: 1

penartur
penartur

Reputation: 9912

What about ^(.*)(\d{2})\-(\d{2})\-(\d{4})$? It will parse your string into four parts: JonSmith, 02, 11 and 1955.

Upvotes: 2

DaveRandom
DaveRandom

Reputation: 88667

preg_match('/([a-z]+)([0-9-]+)/i', 'JonSmith02-11-1955', $matches);
echo "Name is $matches[1]<br>\n";
echo "Birth date is $matches[2]<br>\n";

See it working

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816462

/(?<=[a-z])(?=\d)/i

works in this case. It matches a position preceded by a letter and followed by a digit. Read about lookbehinds and -aheads for more information.

This won't work if the name can contain digits.

DEMO

Upvotes: 4

Related Questions