How can I check if a word is contained in another string using PHP?-ThrowExceptions

Exception or error:

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.

How to solve:

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;
}

Answer:

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”

Answer:

use:

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

or

return (stripos($text,$word) !== false); //case-insensitive

Answer:

strpos

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

if ($pos === false) {
    return false;
} else {
    return true;
}
?>

Answer:

$text="I go to school";
return (strpos($text, 'to')!== false);

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

Answer:

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

if (strstr($haystack, $needle)) {
   return true;
} else {
   return false;
}

Answer:

You can use these string functions,

strstr — Find the first occurrence of a string

stristr — Case-insensitive strstr()

strrchr — Find the last occurrence of a character in a string

strpos — Find the position of the first occurrence of a substring in a string

strpbrk — Search a string for any of a set of characters

If that doesn’t help then you should use preg regular expression

preg_match — Perform a regular expression match

Answer:

@mrclay

cant’ we simply do

"/(?:^|\w+)" . preg_quote($word, '/') . "(?:$|\w+)/i"

so that it either checks starting or whitespace, and ending or whitespace.

Answer:

After searching so many times for a suitable php version, I decide to write my own contains function (with more than one parameter needles) and good to remember.

function contains($str,$contain)
{
    if(stripos($contain,"|") !== false)
        {
        $s = preg_split('/[|]+/i',$contain);
        $len = sizeof($s);
        for($i=0;$i < $len;$i++)
            {
            if(stripos($str,$s[$i]) !== false)
                {
                return(true);
                }
            }
        }
    if(stripos($str,$contain) !== false)
        {
        return(true);
        }
  return(false);
}

Description of php contains:

contains($str,$arg)

$str: The string to be searched
$arg: The needle, more arguments divided by '|'

Examples:

$str = 'green house';
if(contains($str,"green"))
    echo "we have a green house.";
else
    echo "our house isn't green";

$str = 'green, blue, red houses'; 
if(contains($str,"green|red"))
    echo "we have a green or red house.";
else
    echo "we have a blue house.";

Answer:

Use strpos function in php .

$text = "I go to school";
$word = "to"
if (strpos($text,$word)) {
    echo 'true';
}

Answer:

str_contains () in PHP 8

https://wiki.php.net/rfc/str_contains

Less than 25 years later, and here in PHP they added (https://github.com/php/php-src/commit/1668ad7cb17213e67e42994e0c6911e302a3c3c5) a function that checks whether a line is contained in another line.

str_contains (string $ haystack, string $ needle): bool

str_contains ("abc", "a"); // true
str_contains ("abc", "d"); // false

Of course, this is just the equivalent.
strpos ($ haystack, $ needle)! == false
but a pleasant trifle.

As alternatives to working with strings, there is already symfony / string (https://github.com/symfony/string) or, for example, voku / Stringy (https://github.com/voku/Stringy/).

Leave a Reply

Your email address will not be published. Required fields are marked *