Search code examples
phpregexregex-groupregex-greedyregex-alternation

RegEx for capturing digits in a string (PHP)


I am pulling in job numbers and matching them to data in a mysql database, then retrieving the matching data.

If my job number is 123456 then it matches up fine and I get results. Some are 123-456 some are 12-text, while some are 12-text-345

$variable = $variable

I tried matching the variable but that's what's not effective. I tried changing the SQL within PHPMyAdmin and it doesn't even work smoothly there. I googled and think I should be using RegExp. I tried. I can add a slash and make it work on individual items, however, I do not know where the hyphen will be amidst a massive array. It might be the third or fourth character. I tried pregmatch but I don't think I know what I'm doing with that. I'm looking for a few lines of code to analyze a PHP variable and both detect and escape any meta characters if there are any. A tutorial link would be fine too, I appreciate any assistance


Solution

  • Here, if we wish to only get the numbers, on way would be to collect our digits in a capturing group and then collect everything else, then replace it with just $1, with an expression similar to:

    (\d+)|\D+
    

    Test

    $re = '/(\d+)|\D+/m';
    $str = 'text-12-text-345';
    $subst = '$1';
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    Output

    12345
    

    DEMO