fork download
  1. <?php
  2.  
  3. $format='(212) ### ### ##';
  4. $phone='(212) 121 333 45';
  5.  
  6. // Quote any characters such as ( in the format so they match the input literally
  7. // $regex == \(212\) ### ### ##
  8. $regex = preg_quote($format, '/');
  9.  
  10. // Then surround any groups of #s with parens, making them capturing groups
  11. // $regex == \(212\) (###) (###) (##)
  12. $regex = preg_replace('/#+/', '(\0)', $regex);
  13.  
  14. // Finally, replace the placeholder # with \d and surround with quotes
  15. // $regex == /\(212\) (\d\d\d) (\d\d\d) (\d\d)/
  16. $regex = '/'.str_replace('#', '\d', $regex).'/';
  17.  
  18. if (preg_match($regex, $phone, $matches)) {
  19. echo "Matched: ".implode('', array_slice($matches, 1));
  20. }
  21. else {
  22. echo "No match";
  23. }
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Matched: 12133345