PHP extracts numbers in a string

Source: Internet
Author: User

The recent work in the code to write in a string of all the numbers to be extracted out of such a small function, the study of the discovery method is quite many, it is worth recording, so how to use PHP to extract the number of strings in the function of a small summary, summed up three ways are as follows:

The first method uses a regular expression:

functionFindNum ($str= ' '){    $str=Trim($str); if(Empty($str)){return‘‘;} $reg= '/(\d{3} (\.\d+)?) /is ';//regular expressions that match numbers    Preg_match_all($reg,$str,$result); if(Is_array($result) &&!Empty($result) &&!Empty($result[1]) &&!Empty($result[1] [0])){        return $result[1] [0]; }    return‘‘;}

The second method uses the In_array method:

functionFindNum ($str= ' '){    $str=Trim($str); if(Empty($str)){return‘‘;} $temp=Array(' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' 0 '); $result= ' ';  for($i= 0;$i<strlen($str);$i++){        if(In_array($str[$i],$temp)){            $result.=$str[$i]; }    }    return $result;}

The third method uses the Is_numeric function:

functionFindNum ($str= ' '){    $str=Trim($str); if(Empty($str)){return‘‘;} $result= ' ';  for($i= 0;$i<strlen($str);$i++){        if(Is_numeric($str[$i])){            $result.=$str[$i]; }    }    return $result;}

PHP extracts numbers in a string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.