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


i've string can this:

)250 w (501 ps 20 ps 50 ps lpg)                                  246 kw (334 ps 

i want 501, 20, 50 , 334 respectively. in other words: digit before ps or ps(case insensitive).

i tired this, doesn't work cases shown above:

$str = 'lpg)                                  246 kw (334 ps'; preg_match('/\d+(.*?)ps/',$str, $m); print_r($m); 

how can change code work every possible string shown above?

just use regex:

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

explanation:

  • 1st capturing group (\d+)
  • \d+ match digit [0-9]
    • quantifier: + between 1 , unlimited times, many times possible, giving needed [greedy]
  • \s* match white space character [\r\n\t\f ]
    • quantifier: * between 0 , unlimited times, many times possible, giving needed [greedy]
  • ps matches characters ps literally (case insensitive)

flags:

  • i modifier: insensitive. case insensitive match (ignores case of [a-za-z])

Comments