Skip to content
Advertisement

regex preg_replace php

I have random variable like: Strip @ 489.000 Strip 1 @ 489.000 Strip 2 @ 589.000

I need output will be: only number after ‘anything @ ‘ 489.000

so give me output: 489.000 489.000 589.000

hot to achive this use php regex?

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

Advertisement

Answer

To get all matches, use

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

To get the first match, use

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

Details

  • S – a non-whitespace char
  • s – a whitespace
  • @ – a @ char
  • s+ – 1+ whitespaces
  • K – match reset operator
  • d+ – 1+ digits
  • (?:.d+)? – an optional sequence of a dot and 1+ digits.

See the regex demo.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement