tags:

views:

352

answers:

6

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.

+2  A: 

strpos

<?php
$text = "I go to school";
$word = "to"
$pos = strpos($text, $word);

if ($pos === false) {
    return false;
} else {
    return true;
}
?>
jitter
+1  A: 
$text="I go to school";
return (strpos($text, 'to')!== false);

The manual page you need to find the correct usage of strpos

Eineki
+5  A: 

use:

return (strpos($text,$word) !== false); //case-sensitive

or

return (stripos($text,$word) !== false); //case-insensitive
Jonathan Fingland
You got'em backwards. stripos is case-insensitive.
Tordek
haha, quite right and obviously so. fixed
Jonathan Fingland
@Itay, thanks for changing it
Jonathan Fingland
+1  A: 

Another way (besides the strpos examples already given is to use the 'strstr' function:

if (strstr($haystack, $needle)) {
   return true;
} else {
   return false;
}
ylebre
+3  A: 

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;
}
pix0r
+1  A: 
function hasWord($word, $txt) {
    $patt = "/(?:^|[^a-zA-Z])" . preg_quote($word, '/') . "(?:$|[^a-zA-Z])/i";
    return preg_match($patt, $txt);
}

If $word is "to", this will match:

  • "Listen to Me"
  • "To the moon"
  • "up-to-the-minute"

but not:

  • "Together"
  • "Into space"
mrclay