doucan4815
doucan4815
2013-03-26 05:06
浏览 51
已采纳

用preg_match检查一些单词

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • douyingp82418
    douyingp82418 2013-03-26 05:22
    已采纳

    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.

    点赞 评论
  • doyp9057
    doyp9057 2013-03-26 05:13

    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.

    点赞 评论
  • dongpo2014
    dongpo2014 2013-03-26 05:15

    try using this

            $pattern = '%(?=.*[0-9])(?=.*\.)%';
            if (preg_match($pattern, 'MY_WORD_HERE'))
            {
               echo 'ok';
            }
    
            ?>
    
    点赞 评论
  • dongmozhui3805
    dongmozhui3805 2013-03-26 05:24
    $pattern = '#^([\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})$#';
    
    点赞 评论

相关推荐