Reputation: 1437
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
Reputation: 140833
^([a-zA-z]*)([0-9]*)\-(.+)*$
For this example :
JonSmith02-11-1955
Give :
JonSmith
02
11-1955
Upvotes: 1
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
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
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";
Upvotes: 0
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.
Upvotes: 4