How can I use file_get_contents to search for the word "team" in the site and if it finds the word echo the word?
<?php
$content = file_get_contents( 'https://www.hostgator.com.br' );
$busca = 'equipe ';
?>
How can I use file_get_contents to search for the word "team" in the site and if it finds the word echo the word?
<?php
$content = file_get_contents( 'https://www.hostgator.com.br' );
$busca = 'equipe ';
?>
You can use preg_match_all()
to do 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);
Use the strpos
function 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";
}
If you need to find the word that is case-sensitive, you can use stripos
.
Regular expressions are often slower. If the string is just a specific word, you can choose strpos
, which is simpler.
It can be done in the following ways, and it has many other ways:
In that first one, going through line by line and giving echo in 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 by 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>';
}
}