Search word with file_get_contents

Asked

Viewed 699 times

6

How can I use file_get_contents to search for the word "team" on the site and if it locates the word echo in the word?

<?php

$content = file_get_contents( 'https://www.hostgator.com.br' );

$busca = 'equipe ';

?>
  • 1

    Do you say search for a team within the returned html? or do a team search in the site search box and get the result ?

  • search for a team within html

  • if he finds the word team in html give an echo with the word team

3 answers

5

Can use preg_match_all() to make this search, the results are stored in the third argument($matches).

<?php
   $content = file_get_contents( 'https://www.hostgator.com.br' );
   $regex = '/equipe/';
   preg_match_all($regex, $content, $matches);

   echo "<pre>";
   print_r($matches);
  • 1

    My strpos it’s faster! ná ná ná ná ná ná ná ná!

  • @Wallacemaxters I went 11 seconds faster than the strpos() haha :P

  • I put a little pin in your regex in my reply, kkkkkkk

5

Use the function strpos to find the first occurrence of the string.

$content = file_get_contents( 'https://www.hostgator.com.br' );


if (strpos($content, 'equipe') !== FALSE) {
    echo "tem a palavra";
}

In case I need to find the word independent of upper or lower case, you can use stripos.

Usually regular expressions are slower. If the string is just a specific word, you can choose strpos, which is simpler.

  • Returned nothing.

  • 1

    There is an error in the code. A variable is $contents and another is $content. I’ll fix

  • 1

    I didn’t even notice....

2

It can be done in the following ways, and it also has many other forms:

In the first one going line by line and giving echo in the words found:

<?php

$fileContent = file_get_contents('https://pt.wikipedia.org/wiki/Equipe');

foreach (preg_split('/\n/', $fileContent) as $value) {

  $pattern = '/equipe/';//Padrão a ser encontrado na string $fileContent
  if (preg_match_all($pattern, $value, $matches)) {

    foreach ($matches[0] as $matche) {

      echo $matche . '<br>';

    }

  }

}

Or also this way searching the entire string:

<?php

$fileContent = file_get_contents('https://pt.wikipedia.org/wiki/Equipe');

$pattern = '/equipe/';//Padrão a ser encontrado na string $value
if (preg_match_all($pattern, $fileContent, $matches)) {

  foreach ($matches[0] as $matche) {
    echo $matche . '<br>';
  }

}

Browser other questions tagged

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