cursed Posted November 23, 2009 Share Posted November 23, 2009 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 More sharing options...
cags Posted November 23, 2009 Share Posted November 23, 2009 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 More sharing options...
cursed Posted November 23, 2009 Author Share Posted November 23, 2009 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 More sharing options...
cags Posted November 23, 2009 Share Posted November 23, 2009 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 More sharing options...
cursed Posted November 23, 2009 Author Share Posted November 23, 2009 alright, thanks! Link to comment https://forums.phpfreaks.com/topic/182683-quick-strpos-problem/#findComment-964239 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.