php - How can I get difference using preg_match -


<?php $format='(212) ### ### ##'; $phone='(212) 121 333 45'; $format=str_replace('(','\(',$format); $format=str_replace(')','\)',$format); $format=str_replace('.','\.',$format); $format=str_replace('#','[0-9]',$format); $pattern="/^".$format."$/"; //pattern->  /^\(212\) [0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9]$/ if (preg_match($pattern,$phone)) echo 'true'; else echo 'false'; ?> 

input (212) 121 333 45 want result as; 1213345

it's success check. want matched chars same time.

you can little "regex construction" work:

$format='(212) ### ### ##'; $phone='(212) 121 333 45';  // quote characters such ( in format match input literally // $regex == \(212\) ### ### ## $regex = preg_quote($format, '/');  // surround groups of #s parens, making them capturing groups // $regex == \(212\) (###) (###) (##) $regex = preg_replace('/#+/', '(\0)', $regex);  // finally, replace placeholder # \d , surround slashes // $regex == /\(212\) (\d\d\d) (\d\d\d) (\d\d)/ $regex = '/'.str_replace('#', '\d', $regex).'/'; 

now 're ready roll:

if (preg_match($regex, $phone, $matches)) {     echo "matched: ".implode('', array_slice($matches, 1)); } else {     echo "no match"; } 

the construct array_slice($matches, 1) creates array of contents of each capturing group, example input result in array ['121', '333', '45']. implode joins these bits together, producing 12133345.

see in action.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -