Return number with Regular Expression

1

I have a list of articles from Art. 1 through Art. 2040, but in each article there are other numbers.

I would like to make an expression that: 1 - Capture the numbers always after the string "Art." Until the space after the number; 2 - Exclude the points and the symbol "º";

I would like to make a regular expression that would return only the article numbers.

This is the code I used, however, in some articles it generates a strange number

$str = preg_replace('/[^0-9]/', '', $novalinhas);
$artigo = $str;

But so, it takes all the numbers in the string

I solved the question like this:

              preg_match('/[0-9]+/', $novalinhas, $matches);
              $artigo = implode(' ',$matches);
              echo $artigo;

But I do not know if it's the best way.

    
asked by anonymous 22.04.2015 / 05:32

1 answer

4

I do not do PHP in a while, here it :

$artigos = [
    "Art. 1 lala 23",
    "Art. 2 lala 23",
    "Art. 3 lala 23",
    "Art. 4345 lala 23",
    ];
$artigos_len = count($artigos) -1;

for ($i=0; $i <= $artigos_len; $i++) {
    preg_match("/Art\. (\d+)/i",$artigos[$i],$match);
    echo "<ul class='artigo {$match[1]}'></ul>\n\r"

}

The important part here is preg_match("/Art\. (\d+)/i",$artigos[$i],$match); This line picks up, from each item in the list of articles, a regular expression that has to have "Art NUMBER" but does not care about what goes beyond of this.

(\d+) refers to a group of numbers that can have one or more digits, serving for us then we use the $match[1] where 1 is the number of this same group.

    
22.04.2015 / 11:39