I just learned how to validate a text , i know already how to check if the string contains only capital and non capital letters, if its purely numerical but I can't figure out how to put this into code:

The text may contain upper and lower case letters
The text may contain numbers
The text may contain underscores
The text may not contain spaces
The text may not contain other characters besides alphanumerics and underscores
The text may not be = ""

If these conditions are satisfied then the text will be valid otherwise an error will be reported.

Can anyone please help me encode this using regular expression?
Thanks!!!

    check if you have ctype support.

    now $text is the string we gonna evaluate:

    // Strip whitespace from the beginning and end of a string 
    $text = trim($text) 
    
    if (!ctype_space($text)) { // text don't have any spaces
      if(ctype_alnum($text)) {
      // text is alphanumeric, everything is OK.
      }
      elseif (substr_count($text, "_") > 0) {
      // text is NOT alphanum and have at least 1 underscore
      $pieces = explode("_", $text);
    
      // now we check if the pieces are alphanumeric (separated by _)
        for($i = 0; $i < count($pieces); $i++) {
         // we made an array of error codes, 0 if the piece is alphanum, and 1 if NOT.
         if(ctype_alnum($pieces[$i]) $error[$i] = 0; else $error[$i] = 1; 
        }
    
     if(in_array("1", $error)) { echo "ERROR: Please insert an alphanumeric value (can contain underscores)";
     } else {
     // EVERYTHING IS OK.
      }
      } else {
      echo "ERROR: Please insert an alphanumeric value (can contain underscores)";
      } 
    }
    

      try using regular expressions too

      $text="whatever";
      $a=ereg("[A-Za-z0-9_]$",$text);
      $b=ereg("[[:space:]]",$text);
      if($a && !$b)
      	echo "passed";
      

      that might work, i just threw something out-> but look into regxs to validate anything 🙂

        Per the PHP manual, preg_match() "is often faster alternative" than ereg(). Hence, something like this should do the job adequately:

        $text = "someTextStringWithoutSpacesBut01234possiblyNumbers";
        if(preg_match("/^[a-z0-9_]+$/i",$text) && $text != '') {
        	// $text is OK
        } else {
        	// Contains something other than a-z,A-Z,0-9,_ or is an empty string 
        }
        

          Thanks so much!!! All your answers are great!!!

            Write a Reply...