phpregexpreg-replacesanitizationtextmatching

Get all float numbers following an @ symbol


I have random variable like:

Strip @ 489.000
Strip 1 @ 489.000
Strip 2 @ 589.000

I need the output to be only the number after [anything] @ to give me:

489.000
489.000
589.000

How to achieve this using PHP regex?

$string = '  Strip 1 @ 489.000';
$pattern = ' /(\s\S) @ (\d+)/i';
$replacement = '$3';
echo preg_replace($pattern, $replacement, $string);

Solution

  • To get all matches, use

    if (preg_match_all('/\S\s@\s+\K\d+(?:\.\d+)?/', $text, $matches)) {
        print_r($matches[0]);
    }
    

    To get the first match, use

    if (preg_match('/\S\s@\s+\K\d+(?:\.\d+)?/', $text, $match)) {
        print_r($match[0]);
    }
    

    Details

    See the regex demo.