PHP MySQL Tutorial
Learn PHP and MySQL

Finding Sub-Strings using PHP

100% of people found this useful
Finding Sub-Strings using PHP

PHP already have the function that check if a substring exists in another string. It's called strpos(). This function returns the position of substring when the substring is found and return false otherwise. Using the example string you gave me the code will look like this :

$string = "walawalabingbang";
$substring = "bing";
if (strpos($string, $substring) !== false) {
   // Yes, '$substring' is found in '$string';
   // ... do whatever you wish down here
} else {
   // Nope, can't find '$substring' in '$string';
   // ... do something here?
}


Please remember that when you're using strpos() always use the === or !== operator to test for equality / inequality instead of == or !=. Here's the reason. If you're testing the existence of "wala" in the string then the result of strpos("walawalabingbang", "wala") is zero. Since php treat zero as false the result of strpos("walawalabingbang", "wala") != false is false so even though the substring is found right there at the beginning you would end up going to the else block

Recent Comments

Leave the first comment for this page.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems