I need to check some words with preg_match
. If the words contain numbers and .
, I want to echo "ok".
Lets say i want to ckeck this :
4814.84dszs //ok
412.84.61.412 //ok
hello.4you //ok
welcome.user //not ok
481221222 // not ok
I have used this:
if (preg_match('/^[0-9][.]+$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
But it doesn't give me the exactly result which I looking for.
Try this :
if (preg_match('/(\d+\.)|(\.\d+)/', '4814.84dszs'))
{
echo 'ok';
}
^
-> indicates at the begining of the string
$
-> End of the string.
So your pattern says from start to end(Matching for whole string)
If you remove this it will match anywhere in the string not whole string.
Use this:
if (preg_match('/([0-9]+[\.]+|[\.]+[0-9]+)$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
"+" (plus sign) means 1 or more occurrences of the matched expression
You can also use this if the . and the numbers are not following each other and there are other chars in the middle:
if (preg_match('/([0-9]+[^0-9\.]*[\.]+|[\.]+[^0-9\.]*[0-9]+)$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
Explanation: it checks if there is a digit followed by dot or if there's a dot followed by a digit or even if there's a digit followed by other chars then a dot or vice versa.
try using this
$pattern = '%(?=.*[0-9])(?=.*\.)%';
if (preg_match($pattern, 'MY_WORD_HERE'))
{
echo 'ok';
}
?>
$pattern = '#^([\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})$#';