PHP Find Variable in String
Since I always try to remember what this PHP code is, and I can never remember, I thought I’d add it to my blog so I never forget.
This searches a string of text and finds a user defined variable. Very handy.
$string = "PHP";
$container = "I love writing PHP code.";
if(strstr($container,$string)) {
echo "found it.";
} else {
echo "not found.";
}













Here’s another way to get the same result:
$string = “PHP”;
$container = “I love writing PHP code.”;
echo (strstr($container,$string)?”found it.”:”not found.”);
- collideous November 1st, 2005 at 10:27 am
Mozilla Firefox 1.0.7 - Windows XP
Hi,
I have used the original method since it allows me to execute certain code based upon found or not found criteria. This article was very helpfull to me.
Thanks
- Anurag Tarar January 12th, 2006 at 3:52 am
Mozilla Firefox 1.0.6 - Windows XP
Thanks !
This is exactly what i am looking for
Vinit
- Vinit August 8th, 2006 at 5:35 pm
Internet Explorer 6.0 - Windows XP
Thank you, thank you, thank you!
- Jason September 10th, 2006 at 10:23 pm
Mozilla Firefox 1.5.0.6 - Mac OS X
yeah, I don’t know why PHP net always has the complicated jibba jabba when dummies like myself use that site as well. I searched high and low for about ten minutes just now until you solved my problem in laymens terms. Thanks!
- me August 19th, 2007 at 5:01 pm
Internet Explorer 6.0 - Windows XP
damn cant belive i always forget this one!
- douche August 27th, 2007 at 11:36 am
Opera 9.10 - Windows XP
douche - That’s exactly why I posted it.
- Thomas August 29th, 2007 at 8:06 pm
Mozilla Firefox 2.0.0.5 - Mac OS X
… and for insensitive search like Jane, jaNE, or JANE
- ontengen October 29th, 2007 at 7:55 pm
Mozilla Firefox 2.0.0.7 - Windows XP
$haystack=”Hi jane, you look great.”;
$needle=”jaNe”;
if (stristr($haystack,$needle)){
print “Yup! i found it.”;
}
else{
print “Nope, i don’t see it.”;
}
- ontengen October 29th, 2007 at 7:57 pm
Mozilla Firefox 2.0.0.7 - Windows XP
THANKS! I really needed this! YOU ROCK!
- sumsumin December 8th, 2007 at 2:14 pm
Mozilla Firefox 2.0.0.11 - Windows XP
Thank you, I searched all over for this
- Greg December 11th, 2007 at 7:16 pm
Mozilla Firefox 2.0.0.11 - Windows XP
You, are, Legend.
Exactly the last piece to my puzzle!
Was struggling to write a “if .co.uk is in string then..” statement.
- Paul January 8th, 2008 at 3:44 pm
Internet Explorer 6.0 - Windows XP
it’s cool but it can result only one.
what can i do to get all find results.
for example in
“hello. i am a php developer. i am darklord”
when i serach
“i am”
there are 2 in this paragraph.
- darklord May 14th, 2008 at 12:46 pm
Mozilla Firefox 2.0 - Windows XP
nice.
Thanx.
- Ben Althauser May 15th, 2008 at 4:18 am
Internet Explorer 7.0 - Windows Vista