#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    2
    Rep Power
    0

    Create a regex that will return true or false


    Please help me to create a regex condition using preg_match that will return true or false if the below conditions meet.


    no spaces
    AND
    one or more letters
    AND
    one or more numbers
    AND
    6 characters or more
    AND
    optionally a hyphen
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,959
    Rep Power
    9397
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    2
    Rep Power
    0
    Originally Posted by requinix
    What have you tried so far?
    Hi,

    Below sample is the sample code
    Code:
    <?php
    //$sample_text = '%%%%%%%%'; // must failed
    //$sample_text = '123'; // must failed
    //$sample_text = 'ASDD'; // must failed
    //$sample_text = '12344A'; //  pass
    //$sample_text = 'aaaaad1'; //  pass
    
    $sample_text = '%%%%%%%%'; // must failed
     
    
    
    function checkText($sample_text){
    	$regex  = '/[a-zA-Z0-9]{6,}/';
    	$sku = false;
    	if (preg_match($regex,$sample_text)) {
    	  	$sku = true;
    	} 
     	return $sku;
    }
    
    if(checkText($sample_text) == 'true'){
    	echo 'true';
    }else{
    	echo 'false';
    }
    ?>
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    Hi,

    If you want to check the whole string with a regex, you need to use the anchors "^" and "$" for the beginning and the end of the string. Otherwise the regex will also match substrings.

    PHP Code:
    '/^[a-z0-9]{6,}$/i' 
    You also seem to be confused with booleans. When your function returns a boolean (i. e. true or false), it makes absolutely no sense to check it with the string(!) 'true'. Languages with a strict type system wouldn't even allow this.

    Why don't you simply check the value directly?

    PHP Code:
    if (checkText($sample_text)) ... 
    Apart from that, I'm not really sure what this has to do with your original question. Your regex simply checks for a string consisting of at least 6 alphanumeric characters.
    Last edited by Jacques1; August 28th, 2012 at 04:04 AM.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo