Search code examples
phppreg-match

how to check the special chars like ( >, < ,-, 0-9) exists in string using preg_match in PHP


I want to check only string contains ( >, <, -, 0-9) using preg_match, If exists return true. Here is my trial :

   $page_num  ="25-100"; or $page_num = ">300";
  if (preg_match('/[0-9]+<+>/', $page_num))
  {
   return true;
  }

Solution

  • Here is the correct regex :

    if (preg_match('/[><\-0-9]/', $page_num))
    

    If you want to check if all characters are one of these (^ and $ force the string to contain only these characters from the start of the string untill the end) :

    if (preg_match('/^[><\-0-9]+$/', $page_num))