1

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

1 Answer 1

1

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

Click for Demo

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 digits

Click here to see the Code and Output

enter image description here

Sign up to request clarification or add additional context in comments.

8 Comments

(+1) but consider using anchors as well, it reduces the steps needed dramatically: regex101.com/r/4mU8kv/2
Updated. You are correct. The no. of steps were less when I used the ^ anchor.
thanks its works ,but some time the phone number appear like this (999) how can i add something to the regex to catch it and print it?
(999)? A 3-digit phone number? Could you pls give an example?
like this :09/27/17 3:00p sam1, sam 15 (999) 17 09/27/17 3:30p mark1,
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.