How does PHP extract the numbers in a string? Summary of methods for extracting numbers from a string in PHP (with code)

Source: Internet
Author: User
What this article brings to you is about how PHP extracts the numbers in a string. PHP extract the number of strings in the method summary (with code), there is a certain reference value, the need for friends can refer to, I hope to help you.

PHP extracts the first set of numbers in a string

<?php    $str = ' acc123nmnm4545 ';    if (Preg_match ('/\d+/', $str, $arr)) {       echo $arr [0];    }? >

Other ways in which PHP extracts numbers from a string

The first method uses a regular expression:

function FindNum ($str = ") {$str =trim ($STR), if (Empty ($STR)) {return ';} $reg = '/(\d{3} (\.\d+)?) /is ';//match number of regular expression 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:

function FindNum ($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:

function FindNum ($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;}

For example:

Intercept the number in the string 2    $str = ' Q 2 ';    $result = ";    for ($i =0; $i <strlen ($STR), $i + +) {        if (is_numeric ($str [$i])) {            $result. = $str [$i];        }    }    Print_r ($result);d ie;    Output Results 2

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.