jadoon
jadoon

Reputation: 11

i want to build regular expression to extract substring from string in php

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

Answers (3)

alex
alex

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);

Output

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'];

See it on ideone.com

Upvotes: 2

Gumbo
Gumbo

Reputation: 655269

You can use preg_split to split the string at the keywords:

$parts = preg_split('/(date created|phone|location):/', $str);

Upvotes: 2

powtac
powtac

Reputation: 41050

preg_match('~date created:(.*)phone:(.*)Location:(.*)~', $string, $matches);
var_dump($matches);

Upvotes: 1

Related Questions