Reputation: 21
I am trying to check if a string contains an exact sentence.
Example:
$sentence = "welcome to";
$string = "hello and welcome to my website.";
if(strpos($string, $sentence) !== false) {
//found PART of "welcome to" in the $string
//Only want it to come back true is it contains "welcome to".
}
I now want to check if it contains exactelly "welcome to". Not "come to" or "welcome"... The exact value of $sentence. Also it needs to be dynamic. So checking from a variable against a variable that could contain any sentence.
Thanks. Martin.
Upvotes: 0
Views: 2251
Reputation: 74217
Using preg_match()
will be better to get an exact match and using the \b
word boundary.
$string = "hello and welcome to my website.";
if ( preg_match("~\bwelcome to\b~",$string) ){
echo "Match found.";
}
else{
echo "No match found.";
}
While doing:
~\bcome to\b~
won't be a match.
Edit:
// will match
$sentence = "welcome to";
// will not match
// $sentence = "come to";
$string = "hello and welcome to my website.";
if(preg_match("~\b".$sentence."\b~", $string)){
echo "An exact match was found.";
}
else{
echo "No exact match was found.";
}
To add case-insensitivity use the i
switch:
if (preg_match("#\b".$sentence."\b#i",$string))
Upvotes: 2
Reputation: 1538
$sentence = "welcome to";
$string = "Hello and welcome to my website";
if( strstr($sentence, $string)) {
// Your code here if $sentence contains $string
}
else{
// If no contains
}
Upvotes: -1