lobirkeland lobirkeland - 5 months ago 8
PHP Question

Keep only numbers between specific letters

I want to keep a value in several separated long text strings with one part in common. One of the text strings:

N-05-0040(119) f 2005 svart hp Ml:153 - 160 - 20 - 75 Tot 31- 3- 3- 6- 13 (4)29,7M - (4)28,2aK Kr 204.500, 2pr 2010, Trener: Ole Olesen


The common part is "Kr 204.500," and I only need the numbers, so I can use them for calculations later.

Jan Jan
Answer

To get the digits/points after Kr, you could use the following expression:

Kr\h*    # Kr as string, followed by spaces or tabs
([.\d]+) # capture numbers like 123, 12.5 into the first group

See a demo on regex101.com.


In PHP:

<?php
$string = 'N-05-0040(119) f 2005 svart hp Ml:153 - 160 - 20 - 75 Tot 31- 3- 3- 6- 13 (4)29,7M - (4)28,2aK Kr 204.500, 2pr 2010, Trener: Ole Olesen';

$regex = '~
            Kr\h*    # Kr as string, followed by spaces or tabs
            ([.\d]+) # capture numbers like 123, 12.5 into the first group
          ~x';

preg_match_all($regex, $string, $matches);
print_r($matches);
?>

See a demo on ideone.com.

Comments