Reputation: 43
I have a php script that reads a text file. This text file looks like this.
09/27/17
3:00p
sam1,
sam
15
(999)
999-9999
M:(888)
888-8888
17
09/27/17
3:30p
mark1,
marke
asd
15
(777)
777-7777
M:(666)
666-6666
17
What I need to do is extract the phone number but the problem is the phone number is splitted in two line as you see so
My PHP script:
$string = "";
$date=array();
$data1 = file("data.txt");
for($i =0; $i < count($data1);$i++)
{
$data = explode(" ",$data1[$i]);
$line = $data[0];
//$string .=$line;
if (preg_match('^[M:]\([0-9]{3}\)[0-9]{3}-[0-9]{4}/s^',$line)) {
$string .= $line."\n";
}
if (preg_match('^\([0-9]{3}\)[0-9]{3}-[0-9]{4}/s^',$line)) {
$string .= $line."\n";
}
}
I need it to be like so:
(999)999-9999,M:(888)888-8888
(777)777-7777,M:(666)666-6666
but I am not getting any result because the regex is not valid
What is the correct regex to achieve this? thanks
Upvotes: 1
Views: 75
Reputation: 10360
Try this Regex. The required mobile number can be formed by concatenating what is present in Group1 and Group2 of each of these matches.
^((?:M:)?\(\d{3}\))\s*(\d{3}-\d{4})
Explanation:
((?:M:)?\(\d{3}\))
- Capturing group 1
(?:M:)?
- Matches 0 or 1 occurrences of the letter M
\(
- matches (
literally\d{3}
- matches 3 digits\)
- matches )
literally\s*
- matches 0 or more white space characters(\d{3}-\d{4})
- 2nd Capturing group containing the sequence of 3 digits followed by a -
followed by another 4 digitsClick here to see the Code and Output
Upvotes: 1