Reputation: 11
I have a string like this: "date created:12 march 1996phone:33444567Location:california steet 5"
date created
, phone
and location
are fixed but their value is changing. I want to extract them from string and want to display them separate.
Upvotes: 0
Views: 774
Reputation: 490263
This should do it...
$str = 'date created:12 march 1996phone:33444567Location:california steet 5';
preg_match_all('/^date created:(?<date_created>.*?)phone:(?<phone>.*?)Location:(?<location>.*?)$/', $str, $matches);
var_dump($matches);
array(7) {
[0]=>
array(1) {
[0]=>
string(67) "date created:12 march 1996phone:33444567Location:california steet 5"
}
["date_created"]=>
array(1) {
[0]=>
string(13) "12 march 1996"
}
[1]=>
array(1) {
[0]=>
string(13) "12 march 1996"
}
["phone"]=>
array(1) {
[0]=>
string(8) "33444567"
}
[2]=>
array(1) {
[0]=>
string(8) "33444567"
}
["location"]=>
array(1) {
[0]=>
string(18) "california steet 5"
}
[3]=>
array(1) {
[0]=>
string(18) "california steet 5"
}
}
This uses named capturing groups so you can access the data with...
// Example only, of course this is as bad as using `extract()`
$date_created = $matches['date_created'];
$location = $matches['location'];
$phone = $matches['phone'];
Upvotes: 2
Reputation: 655269
You can use preg_split
to split the string at the keywords:
$parts = preg_split('/(date created|phone|location):/', $str);
Upvotes: 2
Reputation: 41050
preg_match('~date created:(.*)phone:(.*)Location:(.*)~', $string, $matches);
var_dump($matches);
Upvotes: 1