t_machine Posted March 25, 2007 Share Posted March 25, 2007 Hi, I am wondering if someone could help with this. I would like to check if a word exist in a string and if yes do something. example: $string = 'This website is cool'; How to I check if the word 'website' exists in that string? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/44253-how-to-check-if-text-exist-in-a-string/ Share on other sites More sharing options...
psychohagis Posted March 25, 2007 Share Posted March 25, 2007 use ereg() or eregi() http://www.php.net/ereg http://www.php.net/eregi Quote Link to comment https://forums.phpfreaks.com/topic/44253-how-to-check-if-text-exist-in-a-string/#findComment-214917 Share on other sites More sharing options...
cmgmyr Posted March 25, 2007 Share Posted March 25, 2007 try this: <?php $string = 'This website is cool'; $find = 'website'; if(strstr($string, $find)){ echo "This has $find in it!"; }else{ echo "This does not have $find in it!"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/44253-how-to-check-if-text-exist-in-a-string/#findComment-214925 Share on other sites More sharing options...
t_machine Posted March 25, 2007 Author Share Posted March 25, 2007 Thank you both very much for the help Either of eregi or cmgmyr's example works great for what I needed. Quote Link to comment https://forums.phpfreaks.com/topic/44253-how-to-check-if-text-exist-in-a-string/#findComment-214952 Share on other sites More sharing options...
cmgmyr Posted March 25, 2007 Share Posted March 25, 2007 no problem, glad we could help. make sure you mark the topic as "solved" Quote Link to comment https://forums.phpfreaks.com/topic/44253-how-to-check-if-text-exist-in-a-string/#findComment-214960 Share on other sites More sharing options...
Orio Posted March 25, 2007 Share Posted March 25, 2007 I don't want to be annoying or something (because the problem is already solved), but I think it's better to use strpos(). From the manual, the strstr() function: Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead. And here's how you do it (allow me to use your example, cmgmyr): <?php $string = 'This website is cool'; $find = 'website'; if(strpos($string, $find) !== FALSE){ echo "This has $find in it!"; }else{ echo "This does not have $find in it!"; } ?> Orio. Quote Link to comment https://forums.phpfreaks.com/topic/44253-how-to-check-if-text-exist-in-a-string/#findComment-214963 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.