php check string is contains a substring
Use php to check a string contains substring there maybe many ways, the strpos maybe the most used way, but it’s strange, it not work for me why? That’s what i want to say: the thing you need take care while use strpos .
what’s strpos
Check the php Manual: " strpos — Find position of first occurrence of a string "
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
and for the return value:
"Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE. "
Here is how i use this:
$str = 'google.com'; $find= 'gle.'; if(strpos($str, $find)) { echo "find "; } else { echo "not find"; }
Run it,it seems works correctly.Do you find the problem? For this sample,It work but let’s try this one:
$str = 'google.com'; $find= 'google.'; if(strpos($str, $find)) { echo "find "; } else { echo "not find"; }
It’s show "not find", why? the strpos return 0, not 1 . so even the substring found , it’s still show "not find"
the right way for strpos
Since we know strpos will give a numeric value if found else it is null or false,so let’s see the right way:
$str = 'google.com'; $find= 'google.'; if(is_numeric(strpos($str, $find))) { echo "find "; } else { echo "not find"; }
Or
$str = 'google.com'; $find= 'google.'; $isfound=strpos($str, $find); if($isfound!== false) { echo "find "; } else { echo "not find"; }
So you know more about strpos now,Happy reading!
, I'm a freelancer and available now,if need help just contact me without hesitation.
7 Responses to “php check string is contains a substring”
Leave a Reply
-
Search for:
Categories
- apache (2)
- css xhtml (10)
- html5 (1)
- javascript (3)
- jquery (5)
- magento (3)
- mysql (1)
- php (1)
- SEO Friendly (6)
- Tools (3)
- w3c validation (4)
- Wordpress (4)


















What a great resource!
Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
Great information! I’ve been looking for something like this for a while now. Thanks!
Keep up the good work, I like your writing.
Great site. A lot of useful information here. I’m sending it to some friends!
This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!
very good stuff. Do you have a RSS feed? And will it be cool if I added in your feed to a website of mine? I have a blog which draws content through RSS feeds out of a several websites and I’d like to add yours, a lot of people do not mind because I link back and everything but I like to get consent 1st. Anyway let me know if you can, thanks.