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.
您可以使用preg_split
在关键字处分割字符串:
$parts = preg_split('/(date created|phone|location):/', $str);
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'];
preg_match('~date created:(.*)phone:(.*)Location:(.*)~', $string, $matches);
var_dump($matches);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.