Advertisement
Guest User

Untitled

a guest
Jan 31st, 2015
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. /*
  2. Implement Regular Expression matching algorithm
  3.  
  4. * - match any 0 or more characters
  5. . - match any 1 character
  6.  
  7. Examples:
  8. 1) Pattern - ab*cf , Input - ab bbbbcfddcf (o/p: true), Input - abcf (o/p - true)
  9. 2) Pattern - ab.c , Input - abc (o/p - false), Input - abdc (o/p - true)
  10. */
  11.  
  12. function rexMatch($par, $sar){
  13.  
  14. // Finished and matched
  15. if (empty($par) && empty($sar)){
  16. return true;
  17. }
  18.  
  19. if (!empty($par) && $par[0] == "*" && empty($sar)){
  20. if (count($par)>1){
  21. return false; // there are more chars after *
  22. }else {
  23. return true;// * is last char
  24. }
  25. }
  26.  
  27. // If they are not empty BOTH(check previous IF) then return false
  28. if (empty($par) || empty($sar)){
  29. return false;
  30. }
  31.  
  32. // In case of "." or match just continue with the next one
  33. if ($par[0] == "." || $par[0]==$sar[0]){
  34. return rexMatch(array_slice($par, 1), array_slice($sar, 1));
  35. }
  36.  
  37. // 0 chars, so continue with the next char of pattern and the current char of input
  38. // OR
  39. // more chars, so continue with the next char of input and the current of pattern
  40. if ($par[0] == "*"){
  41. return (rexMatch(array_slice($par, 1), $sar) || rexMatch($par, array_slice($sar, 1)));
  42. }
  43.  
  44. return false;
  45. }
  46.  
  47. function isMatch($pattern, $input){
  48. $par = str_split(trim($pattern));
  49. $sar = str_split(trim($input));
  50. return rexMatch($par, $sar);
  51. }
  52.  
  53. $test = array(
  54. array("*aabc","abc"), //TRUE
  55. array("abc*","abc"), //TRUE
  56. array("ab*cf" , "abbbbbcfddcf"), //TRUE
  57. array("ab*cf" , "abcf"), //TRUE
  58. array("ab*cf" , "abf"), //false
  59. array("ab.c", "abc"), //false
  60. array("ab.c", "abdc"), //TRUE
  61. array("*a.b**cd" , "abbscsdcdlldopcdcd"), //TRUE
  62. );
  63.  
  64. foreach ($test as $t) {
  65. $r = isMatch($t[0], $t[1]) ? "TRUE" : "false";
  66. print "pattern: ".$t[0]." - input: ".$t[1]." ->".$r." \n";
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement