Search code examples
phpregexstringfilteringtext-extraction

Disqualify some elements and isolate trailing number from array of strings


I have various values in a PHP array, that look like below:

$values = ["news_24", "news_81", "blog_56", "member_55", "news_27"];

The first part before the underscore (news, blog, member) is dynamic so I would like to get all the matches in a specific section (news) followed by the numbers.

Something like below:

$section = "news";
$matches = preg_match('$section/[_])GETNUMBER/', $values);

The solution should return 24, 81, and 27, because only these numbers occurred after news and the underscore.


Solution

  • $values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
    
    $section = "news"; 
    foreach($values as $value) {
        $matches = preg_match("/{$section}_(\\d+)/", $value, $number);
        if ($matches)
            echo $number[1], PHP_EOL;
    }