0

I have a PHP variable that holds similar data:

$var = "
Name: Tom
Age: 26
Location: London

Name: Mike
Age: 28
Location: New York

Name: Sunny
Age: 24
Location: Tokyo";

I'd like to extract only the locations, and store them in Array like:

Array
(
    [0] => London
    [1] => New York
    [2] => Tokyo
)

For now, with my simple experience with PHP I'm getting this done using "LOL, Don't Laugh..":

$location = array_merge(preg_replace('/^Location: /','',preg_grep('/^Location: /',explode("\n", $var))));

But I believe, there would be a way better process (maybe with preg_split) to achieve that faster, wiser and with maybe less system over-load.

Kindly, advise.. Thanks in advance.. :-)

Hasan Alsawadi
  • 394
  • 5
  • 15

1 Answers1

1
preg_match_all('/Location: (.+)/', $var, $m);
print_r($m[1]);

That works because the dot doesn't match new line characters, by default.

goat
  • 31,486
  • 7
  • 73
  • 96
  • Hello @rambo-coder, Thanks a lot for the answer.. Would it be better if I used the ^ in the regex to be like: `preg_match_all('/^Location: (.+)/', $var, $m);` Do you think this would be better to make sure Location starts the line?! Again Thanks Alot. – Hasan Alsawadi Jun 14 '12 at 05:39