preg_match()

Does input string match regex expression

  $InputString = "abcd";
  $Length = strlen($InputString);
  $RegexPattern = '^[(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4}$';
  if (
      ($Length > 2) && ($Length < 100) &&    //Testing for length first protects against malicious very long inputs
      (preg_match($RegexPattern, InputString))   //Returns 1 if regex matches
  {

 

  } 

preg_replace()

Replace any characters that don’t match the regex expression with character from another string.

You can make the replacement string empty to simply remove unwanted characters

Remove all characters that are not numbers example
  $InputString = "01-23(4)";
  $RegexPattern = "[^0-9]";
  $FormattedNumber = preg_replace($RegexPattern, "", $InputString)
  //$FormattedNumber = "01234"
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *