How to preg_mach_all in different lines?

Asked

Viewed 21 times

2

<div class="information di-ib mt4">
    Movie (1 eps)<br>
    Aug 2016 - Aug 2016<br>
    380,496 members
</div></div>

I want to make preg_match_all in this code, but I do not know how to do in particular the number of episodes.

  • First, do the [tour] to learn how to use the site correctly. Secondly, you just want to get the number of episodes, in case, the value 1?

  • yes that’s what I want

  • And that value will always be followed by the word eps?

  • yes will always be followed by eps

2 answers

2

If the text has only data from a movie, you can use the function preg_match:

if (preg_match("/\((?P<qtd>\d+) eps\)/", $data, $matches))
{
  echo "O filme possui ", $matches["qtd"], " episódio(s)", PHP_EOL;
}

The output for the text in question would be:

O filme possui 1 episódio(s)

See working on Ideone.

However, if the text contains information from more than one actual film it will be necessary to use the preg_match_all:

if (preg_match_all("/\((?P<qtd>\d+) eps\)/", $data, $matches))
{
  print_r($matches["qtd"]);
}

The only difference is $matches["qtd"] will be a list of values for all films.

See working on Ideone.

The regular expression used in both cases is:

/\((?P<qtd>\d+) eps\)/

Her goal is to find all the groups in the format (X eps), being X an integer value.

  1. The part \( escapes the character ( and indicates the start of the desired group;
  2. The part (?P<qtd>\d+) captures any sequence of numbers, generating the named group qtd;
  3. The part eps makes it necessary for the sequence of numbers to be followed by that text;
  4. The part \) escapes the character ) and indicates the end of the desired group;
  • thank you so much for your help

  • If possible, mark the answer as accepted by pressing the button on the left side of the answer. Still, if you thought the answer was good, you can vote positively on it by pressing the icon ^, also on the left side of the answer.

0

Using preg_match_all:

<?php
$dado = "
<div class='information di-ib mt4'>
    Movie (1 eps)<br>
    Aug 2016 - Aug 2016<br>
    380,496 members
</div>";
preg_match_all("/(?<=\()[\d]/",$dado,$saida,PREG_PATTERN_ORDER);
print_r($saida[0]);//Array ( [0] => 1 )
?>

Ideone test

Explanation of the regex (English)

Browser other questions tagged

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