ankur0101 Posted September 19, 2013 Share Posted September 19, 2013 (edited) Hi, I am really bad when it comes to Regex. Every time, when I need to do things with it, I get confuse. I want to find a word called hello in a variable. something like, $word = "hello"; $target = "hello_guys_howz_life"; Using preg_match, how can I check whether hello word exist in variable $target ? Thanks Edited September 19, 2013 by ankur0101 Quote Link to comment https://forums.phpfreaks.com/topic/282285-check-if-word-exist/ Share on other sites More sharing options...
Solution cataiin Posted September 19, 2013 Solution Share Posted September 19, 2013 if(strpos($target, $word) !== false) { echo "Exists."; } else { echo "Nop."; } Quote Link to comment https://forums.phpfreaks.com/topic/282285-check-if-word-exist/#findComment-1450264 Share on other sites More sharing options...
cataiin Posted September 19, 2013 Share Posted September 19, 2013 with preg_match: if(preg_match("/$word/", $target)) { echo "Exists."; } else { echo "Nop."; } sorry but then I saw you want with preg_match. Quote Link to comment https://forums.phpfreaks.com/topic/282285-check-if-word-exist/#findComment-1450265 Share on other sites More sharing options...
AbraCadaver Posted September 19, 2013 Share Posted September 19, 2013 with preg_match: if(preg_match("/$word/", $target)) { echo "Exists."; } else { echo "Nop."; } sorry but then I saw you want with preg_match. Yes, but try and steer him in the direction of not using regex if it is not needed. As you know strpos() will be much faster than preg. Quote Link to comment https://forums.phpfreaks.com/topic/282285-check-if-word-exist/#findComment-1450271 Share on other sites More sharing options...
Irate Posted September 19, 2013 Share Posted September 19, 2013 Regular expressions are particularly useful for matching patterns, where a normal string function would utterly fail, whereas simple tests for words you already know you want to search for, strpos is the way to go. Quote Link to comment https://forums.phpfreaks.com/topic/282285-check-if-word-exist/#findComment-1450282 Share on other sites More sharing options...
.josh Posted September 19, 2013 Share Posted September 19, 2013 I think saying something would "utterly fail" at something it isn't designed to do in the first place is being a bit harsh and misleading. It's like saying a fish would utterly fail at flying. Well it's not built for the sky in the first place, so if anything is failing, it's your own expectations and/or understanding of it. Quote Link to comment https://forums.phpfreaks.com/topic/282285-check-if-word-exist/#findComment-1450301 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.