Search code examples
phpregexstringpreg-match

How can I extract the number before "PS" (case-insensitive)?


I've a string which can look something like this:

)250 W (501 PS
20 ps
50 ps
LPG)                                  246 kW (334 PS

I want to get 501, 20, 50 and 334 respectively. In other words: The digit just before PS OR ps(case insensitive).

I tired this, but doesn't work for all cases as shown above:

$str = 'LPG)                                  246 kW (334 PS';
preg_match('/\d+(.*?)PS/',$str, $m);
print_r($m);

How can I change my code to work for every possible string as shown above?


Solution

  • Just use this regex:

    /(\d+)\s*ps/i
    

    explanation:

    • 1st Capturing group (\d+)
    • \d+ match a digit [0-9]
      • Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    • \s* match any white space character [\r\n\t\f ]
      • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    • ps matches the characters ps literally (case insensitive)

    flags:

    • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])