Jump to content

Quick Strpos Problem


cursed

Recommended Posts

Apologies for the stupid q in advance.

 

 

Why doesn't strpos find the keyword?

 

<?
$test = "hi";
$page = file_get_contents("http://www.google.com");
function destroyiffound($keyword) {
if(strpos($page, $keyword))
{
$test = "bye";
echo $test;
}
else
echo "wtf";
}
echo $test;
destroyiffound("b");
?>

Link to comment
https://forums.phpfreaks.com/topic/182683-quick-strpos-problem/
Share on other sites

It does, it's just that strpos returns 0 (the position that it's in), which the if statement evaluates as being == FALSE. Proof...

 

$page = file_get_contents("http://www.google.com");
function destroyiffound($keyword) {
if(strpos($page, $keyword)===FALSE) {
   $test = "bye";
   echo $test;
} else
   echo "wtf";
}
echo $test;
destroyiffound("b");

 

EDIT: Ok ignore that, I've put the PEACE PIPE down now. Your right it doesn't find it, because you assign $page outside the function, it's not in scope inside the function. I'd recommend passing it in as a second value.

Link to comment
https://forums.phpfreaks.com/topic/182683-quick-strpos-problem/#findComment-964197
Share on other sites

 

Thanks again cags for solving yet another one of my problems. 

 

I wonder where the solved button went..

 

edit: in your opinion, do you think setting it as a global variable is any good? file_get_contents increases load time by quite a bit, especially with large websites.

especially if I do

destroyiffound("a");

destroyiffound("b");

destroyiffound("c");

 

Link to comment
https://forums.phpfreaks.com/topic/182683-quick-strpos-problem/#findComment-964212
Share on other sites

Global variables are best avoided as much as possible. The exact solution depends on the rest of your code. Personally given the basic example you have their I would pass the url to the function as a second parameter and call file_get_contents from inside the function. But if $page is also used outside of the function simply pass $page as a second parameter.

 

$page = file_get_contents("http://www.google.com");
function destroyiffound($keyword, $page) {
if(strpos($page, $keyword)) {
   $test = "bye";
   echo $test;
} else
   echo "wtf";
}
echo $test;
destroyiffound("b", $page);

Link to comment
https://forums.phpfreaks.com/topic/182683-quick-strpos-problem/#findComment-964224
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.