Myspace Layouts - Premium wordpress themes - Wordpress Themes - Human body - Wordpress Themes

PDA

View Full Version : preg_match and regex problem


zhulq
Jul 17th 2007, 7:20 am
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");

I want just words, digits, white spaces.

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

but how ?

thanks...

nico_swd
Jul 17th 2007, 8:12 am
function alfanumeric($ifade)
{
return preg_match('/^[a-z0-9\s]+$/i', $ifade);
}


\w also matches under scores, so if you only want letters, numbers, and spaces, the above should work.

zhulq
Jul 17th 2007, 10:15 am
The function doesn't return false for double white spaces.

" " like it...

nico_swd
Jul 17th 2007, 10:43 am
Not sure what you mean.


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


Outputs: Is not alfanumeric

Which is true.

zhulq
Jul 17th 2007, 10:53 am
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

nico_swd
Jul 17th 2007, 10:58 am
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);


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);
}

zhulq
Jul 17th 2007, 5:22 pm
thank you thank you thank you :)