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.”);
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
Thanks !
This is exactly what i am looking for 🙂
Vinit
Thank you, thank you, thank you!
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!
damn cant belive i always forget this one!
douche – That’s exactly why I posted it. 🙂
… and for insensitive search like Jane, jaNE, or JANE
$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.”;
}
THANKS! I really needed this! YOU ROCK!
Thank you, I searched all over for this
You, are, Legend.
Exactly the last piece to my puzzle!
Was struggling to write a “if .co.uk is in string then..” statement.
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.
nice. 🙂 Thanx.
Looks like I’m going to have to buy this guy a beer.
thanks, very helpfull!
now i can continue making my own hitcounter!
thanks thanksthanksthanksthanksthanksthanksthanks
Just wanted to say thanks for posting this. I always forget the easiest way to do this and have come across your site every time I look for the solution. You’ve helped me many times.
-AJay
thanks
Thank a lot.
Thanks a lot!
Thanks for this very helpful peice of code
For some reason i always forget this one. they should call it search_str or something
ok, is there a way to search in string for several item previously collected in a array
for example
stristr($haystack,$array_needle)
How to implement with regular expreccion?, example error:
$page = //This is te html content with url to $string
$string = “/^http:\/\/bloat.me\/(.{4})/”;
if(strstr($page,$string)) {
echo “found it.”;
} else {
echo “not found.”;
}
tanks
You should note that your code returns 0 (ie. the equivalent to false) if the needle is found in the very beginning of the haystack (position 0). To prevent this, use strict comparison:
if(strstr($container,$string) === false) {
echo “found it.”;
} else {
echo “not found.”;
}
Thanks for sharing this piece of code, this helped me out a lot!