简体   繁体   English

从字符串中提取9位数字

[英]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. 我基本上在php中有一个包含字符串的数组,我基本上需要过滤该字符串以获取9位ID号(用括号括起来),我确定可以使用正则表达式来做到这一点,但是im毫无章法。

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.... 通过使用preg_replace您只有一个行过滤器。

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

using preg_match 使用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: 好吧,假设它是唯一的一个(用括号括起来的9位数字),则将执行以下操作:

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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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