showkey
showkey

Reputation: 348

To look for a simple way to extract matched parts of strings from an array

I want to extract matched parts of strings --digital part from an array array("HK00003.Day","HK00005.Day").

<?php
$arr=array("HK00003.Day","HK00005.Day");
$result= array();
foreach ($arr as $item){
    preg_match('/[0-9]+/',$item,$match);
    array_push($result,$match[0]);
}

It can get the result :00003 00005,it seems tedious,preg_grep seems simple but the result is not what i want .

preg_grep('/[0-9]+/',$arr);

The output is "HK00003.Day","HK00005.Day", not 00003 00005,
is there more simple way to get the job done?

Upvotes: 1

Views: 51

Answers (4)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

(Here I just get rid off every character in your array which isn't a number with preg_replace())

<?php

    $arr = ["HK00003.Day", "HK00005.Day"];
    $result = preg_replace("/[^0-9]/", "", $arr);

    print_r($result);

?>

output:

Array ( [0] => 00003 [1] => 00005 )

Upvotes: 1

Bo Chen
Bo Chen

Reputation: 436

preg_grep return array entries that match the pattern! Therefore, it returns an array of entry rather than the matching string

try below:

preg_match_all('/[0-9]+/',implode('-',$arr),$result);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use preg_filter (which already uses preg_replace and does not require additional callback functions) to replace the each entry in the array with the number inside:

<?php
   $arr = array("HK00003.Day","HK00005.Day");
   $matches = preg_filter('/^.*?([0-9]+).*/', '$1',$arr);
   print_r($matches);
?>

Output of a sample program:

Array                                                                                                                                                                                                                                                  
(                                                                                                                                                                                                                                                      
    [0] => 00003                                                                                                                                                                                                                                       
    [1] => 00005                                                                                                                                                                                                                                       
)   

Upvotes: 1

Eugene C
Eugene C

Reputation: 530

Your code is fine, not tedious at all. If you want a one-liner you can try something like this (remove everything that's not a digit):

array_push($result, preg_replace("~[^0-9]~", "", $item));

Upvotes: 0

Related Questions