Pseudo Code
text = "I go to school"; word = "to" if ( word.exist(text) ) { return true ; else { return false ; }
I am looking for a PHP function which returns true if the word exists in the text.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
PHP's strstr() function simply takes a string to search, and a chunk of text to search for. If the text was found, it returns the portion of the string from the first character of the match up to the end of the string: $myString = 'Hello, there!'; echo strstr( $myString, 'llo' ); // Displays "llo, there!"
How to check if a string is a keyword? Python in its language defines an inbuilt module “keyword” which handles certain operations related to keywords. A function “iskeyword()” checks if a string is a keyword or not. Returns true if a string is a keyword, else returns false.
You have a few options depending on your needs. For this simple example, strpos()
is probably the simplest and most direct function to use. If you need to do something with the result, you may prefer strstr()
or preg_match()
. If you need to use a complex pattern instead of a string as your needle, you'll want preg_match()
.
$needle = "to"; $haystack = "I go to school";
strpos() and stripos() method (stripos() is case insensitive):
if (strpos($haystack, $needle) !== false) echo "Found!";
strstr() and stristr() method (stristr is case insensitive):
if (strstr($haystack, $needle)) echo "Found!";
preg_match method (regular expressions, much more flexible but runs slower):
if (preg_match("/to/", $haystack)) echo "Found!";
Because you asked for a complete function, this is how you'd put that together (with default values for needle and haystack):
function match_my_string($needle = 'to', $haystack = 'I go to school') { if (strpos($haystack, $needle) !== false) return true; else return false; }
PHP 8.0.0 now contains a str_contains function that works like so:
if (str_contains($haystack, $needle)) { echo "Found"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With