Mirek
Mirek

Reputation: 391

Checking if sentence contains a word in PHP

How can I check if a sentence contains a word. I used names sentence and word instead of string and substring expressly. For example: for sentence

$s = "Ala makota, a kot ma przesrane";

calling function

checkIfContains("kota",$s) 

returns false.

But for

checkIfContains("makota",$s) 

returns true.

Upvotes: 2

Views: 5616

Answers (6)

hacker ninja
hacker ninja

Reputation: 1

you can try like :

if(strpos($s,"kota") !== false){
       echo true;
}

or :

function checkIfContains($string, $letter){
       return strpos($string, $letter) !== false;
}

Upvotes: 0

Structed
Structed

Reputation: 314

$string = "Ala makota, a kot ma przesrane";

checkIfInString("makota", $string);

function checkIfInString($needle, $haystack) {
    $delimiters = ' ,.';
    return in_array($needle, explode($haystack, $delimiters);
}

Upvotes: 0

Fry_95
Fry_95

Reputation: 241

You can try :

function checkIfContains($needle, $haystack) {
    // Remove punctuation marks
    $haystack = preg_replace('/[^a-zA-Z 0-9]+/', '', $haystack);
    // Explode sentence with space
    $haystack = explode(' ', $haystack);
    // Check if $needle exist
    return in_array($needle, $haystack);
}

Upvotes: 0

Berry Langerak
Berry Langerak

Reputation: 18859

If you're looking to match only full words, you'll need a regular expression to accomplish this. Try the following:

<?php
function checkIfContains( $needle, $haystack ) {
    return preg_match( '#\b' . preg_quote( $needle, '#' ) . '\b#i', $haystack ) !== 0;
}

Upvotes: 6

Martin
Martin

Reputation: 6687

You need strpos.

if (strpos($s, 'kota') !== false) { 

}

Or if you insist..

function checkIfContains($needle, $haystack) {
    return (strpos($haystack, $needle) !== false);
}

For full words you could consider regex:

if (preg_match('/\bkota\b/i', $s)) { }

Upvotes: 1

Chris Forrence
Chris Forrence

Reputation: 10094

I'd use explode to separate the string into an array based on a character (" " in this case).

function checkIfContains($toTest, $toCheck)
{
    // Check if length of either string is zero for validation purposes
    if(strlen($toTest) == 0 || strlen($toCheck) == 0)
    {
        return false;
    }
    $exploded = explode(" ", $toCheck);
    foreach($exploded as $word)
    {
         if($word == $toTest)
         {
              // Found a match, return true!
              return true;
         }
    }
    // None matched, return false
    return false;
}

Upvotes: 0

Related Questions