1

I am trying to search through a URL for a matching string, but the below code snippet doesn't seem to work.

<?php

$url = "http://www.drudgereport.com";

$search = "a";
$file = file($url);

if (in_array($search,$file)) {
    echo "Success!";
} else {
    echo "Can't find word.";
}

?>
0

4 Answers 4

2

If you are just searching for an occurrence of a string on the page, you can use

$str = file_get_contents($url);
if (strpos($str, $search) !== false) {
    echo 'Success!';
} else {
    echo 'Fail';
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would I go about looping through the entire contents of $str and counting the number of a's, for example?
@Matt, you don't need a loop as the entire page is loaded as a string into $str. To count occurrences of a string in another string, try substr_count() (php.net/manual/en/function.substr-count.php).
1

in_array() checks if an array member is equal to your needle.

It is improbable many websites will have a line which is equal to a only.

Also, is allow_url_fopen enabled?

Comments

1

That code will only find a line that has the exact $search string (likely including whitespace). If you're parsing HTML, check PHP's DOMDocument classes. Or, you can use a regex to pull what you need.

Comments

0

As @alex says, check is allow_url_fopen is enabled.
Also you can use strpos to search the string:

<?php

$url = "http://www.drudgereport.com";

$search = "a";
$file_content = file_get_contents($url);

if (strpos($file_content, $search) !== false) {
    echo "Success!";
} else {
    echo "Can't find word.";
}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.