Return number with Regular Expression

Asked

Viewed 412 times

1

I have a list of articles from Art. 1 to Art. 2.040., 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 numeral symbol "º";

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

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

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

But like this, it takes all the numbers from the string


I solved the question like this:

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

But I don’t know if it’s the best way.

  • 2

    what you have tried?

  • preg_match_all('/( d+)/', $novalinhas, $Matches); $article = implode($Matches[0]); echo "</ul>"; echo '<ul id="article' . $article . '" class="article">';

  • I put a test here http://preliminarte.com.br/converter.php But in article 6 it goes wrong

  • I would like to make an expression that: 1 - Capture the numbers always after the string "Art. " to the space after the number; 2 - Delete the dots and the numeral symbol "º";

  • 1

    You can edit your question by adding the code and explaining more details of your problem, thereby increasing your chances of getting a quality answer.

1 answer

4


I haven’t done PHP in a while, here goes:

$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 takes, from each item in the article list, a regular expression that has that have "Art. NUMERO" but do not care what goes beyond that.

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

  • cool (+1); maybe preg_match_all ?

  • @Jjoao being that he wants the first number after the word "Art." I do not see why to call the _all when the string only has a possible-match -- so I understood the question, of course :)

  • You are right is unclear (missing an example) (I imagined a text with several occurrences of "Art. d"); but rereading, probably the OP wanted something as references.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.