preg_match and regex problem

Discussion in 'PHP' started by zhulq, Jul 17, 2007.

  1. #1
    Hi,
    My function;

     function alfanumeric($ifade) {
    
        if(preg_match('/([^\w|\s{0,1}])+/i', $ifade)) 
            return false; 
        else                                            
            return true;
      }
    
      echo  alfanumeric("sample user name");
    PHP:
    I want just words, digits, white spaces.

    Function is most return false for double or high white spaces.

    but how ?

    thanks...
     
    zhulq, Jul 17, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    function alfanumeric($ifade)
    {
        return preg_match('/^[a-z0-9\s]+$/i', $ifade);
    }
    
    PHP:
    \w also matches under scores, so if you only want letters, numbers, and spaces, the above should work.
     
    nico_swd, Jul 17, 2007 IP
  3. zhulq

    zhulq Peon

    Messages:
    84
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The function doesn't return false for double white spaces.

    " " like it...
     
    zhulq, Jul 17, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Not sure what you mean.

    
    if (alfanumeric('Hello "quote"'))
    {
    	echo 'Is alfanumeric';
    }
    else
    {
    	echo 'Is not alfanumeric';
    }
    
    PHP:
    Outputs: Is not alfanumeric

    Which is true.
     
    nico_swd, Jul 17, 2007 IP
  5. zhulq

    zhulq Peon

    Messages:
    84
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thank you this true but I want exaclty that.
    
    
    // I have got this variable
    $data="            sample user         name";
    
    // I want this
    $data="sample user name";
    
    // I dont want this
    // white space + white space + white space 
    
    
    Code (markup):
     
    zhulq, Jul 17, 2007 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    I wouldn't bother the user and throw an error for this. I'd just remove the double spaces and continue.

    
    $data = preg_replace('/\s{2,}/', ' ', $data);
    
    PHP:
    If you still want to check for double spaces in the function, you can do:
    
    function alfanumeric($ifade)
    {
        return preg_match('/^[a-z0-9\s]+$/i', $ifade) AND !preg_match('/\s{2,}/', $ifade);
    }
    
    PHP:
     
    nico_swd, Jul 17, 2007 IP
  7. zhulq

    zhulq Peon

    Messages:
    84
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #7
    thank you thank you thank you :)
     
    zhulq, Jul 17, 2007 IP