简体   繁体   中英

extract 9 digit number from a string

I basically have an array in php which contains a string, I basically need to filter the string in order to get a 9 digit ID number (which is surrounded by brackets), im sure there could be a way to do this with regex but im clueless.

I know that regex returns its results as an array as there could be multiple results but I know that there will not be multiple results for each string and therefore I need to put the result straight in to my already existing array if possible

example:

function getTasks(){
   //filter string before inserting into array
   $str['task'] = "meeting mike (298124190)";

   return $str;
}

by using preg_replace you just have one line filter....

 $str['task'] = preg_replace('/.*\((\d{9})\).*/', '$1', "meeting mike (298124190)");

using preg_match

$strings = array("meeting mike (298124190)", "meeting mike (298124190)", "meeting mike (298124190)");
foreach ($strings as $string) {
    if (preg_match("|\(([\d]{9})\)|", $string, $matches)) {
        $str[] = $matches[1];
        // OR $str['task'][] = $matches[1];
    }
}
print_r($str);
<?php
    $str = "meeting mike (298124190)";
    preg_match("/([0-9]{9})/s", $str, $result);

    print_r($result); // $result is an array with the extracted numbers
?>

Well, assuming it is the only one (9 digit number surrounded by brackets) the following will do:

preg_match("|\(([0-9]{9})\)|", $str['task'], $matches);
return $matches[1]; //Will contain your ID.

its somthing like :

$str = "meeting mike (298124190)";
$pattern = '/[0-9]{9}/';
if (preg_match($pattern, $str, $matches))
{

    echo $matches[0];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM