1

i have some data and i want to find out value of it so i try preg_match function it can be easy to finding values i try the the following code to obtain values but i think there is some problem in my code because i am getting value of $a but i try everything to finding value of $a1 here is m sample code

$data=Date:29-05-2016 11:36 - Mo:919530489323 - pdd:9339 - lpm:78JIOP-
pas:sami  
preg_match('#Date:(.*?) (.*?) - Mo:91(.*?) - pdd:(.*?) -
lpm:(.*?) - pas:(.*?)#',$data,$matches);  
$a=$matches[3];
 $a1=$matches[6];

now what i do to get value of $a1 or what is right code for it

chris85
  • 23,846
  • 7
  • 34
  • 51

2 Answers2

1

Replace your last word for regex to match entire word. Currently it returns blank(if you have print_r matches array).

use regex as follow:

preg_match('#Date:(.*?) (.*?) - Mo:91(.*?) - pdd:(.*?) - lpm:(.*?) - pas:(.*)#',$data,$matches);  
B. Desai
  • 16,414
  • 5
  • 26
  • 47
1

Since your last bracket is using laziness mark with wildcard, it will match nothing except other rules require it to. There is no other rules to specify the end of the overall match, so the last part sami is simply skipped by your regular expression. You can examine this:

<?php

$data="Date:29-05-2016 11:36 - Mo:919530489323 - pdd:9339 - lpm:78JIOP - pas:sami";
preg_match('#Date:(.*?) (.*?) - Mo:91(.*?) - pdd:(.*?) - lpm:(.*?) - pas:(.*?)#',$data,$matches);

var_dump($matches);

Which output this:

array(7) {
  [0]=>
  string(70) "Date:29-05-2016 11:36 - Mo:919530489323 - pdd:9339 - lpm:78JIOP - pas:"
  [1]=>
  string(10) "29-05-2016"
  [2]=>
  string(5) "11:36"
  [3]=>
  string(10) "9530489323"
  [4]=>
  string(4) "9339"
  [5]=>
  string(6) "78JIOP"
  [6]=>
  string(0) ""
}

Notice the overall matching string ($matches[0]) value actually stops at the last :. that's why you have an empty string in $matches[6].

Chainging the regular expression will fix the issue:

<?php

$data="Date:29-05-2016 11:36 - Mo:919530489323 - pdd:9339 - lpm:78JIOP - pas:sami";
preg_match('#^Date:(.*?) (.*?) - Mo:91(.*?) - pdd:(.*?) - lpm:(.*?) - pas:(.*?)$#',$data,$matches);         

var_dump($matches);

Notice the ^ and $ I've added. They will match "the beginning of string" and "the end of string". So the string from the last : to the end of whole input string will be included. Which output this:

array(7) {
  [0]=>
  string(74) "Date:29-05-2016 11:36 - Mo:919530489323 - pdd:9339 - lpm:78JIOP - pas:sami"
  [1]=>
  string(10) "29-05-2016"
  [2]=>
  string(5) "11:36"
  [3]=>
  string(10) "9530489323"
  [4]=>
  string(4) "9339"
  [5]=>
  string(6) "78JIOP"
  [6]=>
  string(4) "sami"
}
Koala Yeung
  • 7,475
  • 3
  • 30
  • 50