简体   繁体   English

PHP正则表达式从文件名中提取电话号码

[英]php regex to extract phone numbers from filenames

I'm trying to add filenames with phone numbers in array. 我正在尝试使用数组中的电话号码添加文件名。 My test files are: 我的测试文件是:

dsfdsf543-6786sdfsdfd.jpg
543-6786sdfsdfd.jpg
435-3454
dsfdsf543-6786.jpg
123-4567
543-6786.jpg
345-3454

My goal is different phone numbers will have separate line of elements in array. 我的目标是不同的电话号码将在数组中包含单独的元素行。 Each element in array line will have same phone number. 阵列行中的每个元素将具有相同的电话号码。 For example: 例如:

543-6786 dsfdsf543-6786sdfsdfd.jpg 543-6786sdfsdfd.jpg dsfdsf543-6786.jpg 543-6786.jpg
435-3454
123-4567
345-3454

My code: 我的代码:

$directory = $_SERVER['DOCUMENT_ROOT'];
$handler = opendir($directory);
while ($file = readdir($handler)) {


    if ($file != "." && $file != "..") {
      $regex = "/[\D]*[0-9]{3}-[0-9]{4}[\D]*/";
               preg_match_all($regex, $file, $results);

   }
}
print_r ($results);

Result is 结果是

Array ( [0] => Array ( [0] => 345-3454 ) )

why only one filename in the array? 为什么数组中只有一个文件名? Where is my mistake? 我的错误在哪里? Thank you in advance! 先感谢您!

You're feeding the filenames to preg_match_all one at a time, and each time $result gets overwritten. 您一次将文件名提供给preg_match_all ,每次$result被覆盖。 The thing is to push $results[0] onto an array each time, and then dump that array. 事情是每次将$results[0]推入一个数组,然后转储该数组。

$final_results = [];
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
        $regex = "/[\D]*[0-9]{3}-[0-9]{4}[\D]*/";
        if (preg_match_all($regex, $file, $results) > 0)
            $final_results[] = $results[0] ;
    }
}
print_r ($final_results);

Updated per comment: this version creates a key=>value array where the phone number is the key and the value is all the filenames that contain that number. 每个注释均已更新:此版本创建一个key => value数组,其中电话号码是密钥,而值是包含该号码的所有文件名。

$final_results = [];
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
        $regex = "/[\D]*[0-9]{3}-[0-9]{4}[\D]*/";
        if (preg_match_all($regex, $file, $results) > 0) {
            if empty ($final_results[$results[0]]) {
                $final_results[$results[0]] = $file ;
            } else {
                $final_results[results[0]] .= " ".$file ;
            }
        }
    }
}
print_r ($final_results);

Once you've got this array, it's trivially easy to flatten it to a one-dimensional array like you want. 获得此数组后,可以轻松地将其展平为所需的一维数组。

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

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