我正在尝试检查字符串是否包含确切的句子。
示例:
$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".
}
我现在想检查它是否含有exactelly"欢迎来到"。 不是"来"或者"欢迎" ... $句子的确切价值。 它也需要是动态的。因此,从变量中检查可能包含任何句子的变量。
感谢。马丁。
答案 0 :(得分:2)
使用preg_match()
会更好地获得完全匹配并使用\b
字边界。
$string = "hello and welcome to my website.";
if ( preg_match("~\bwelcome to\b~",$string) ){
echo "Match found.";
}
else{
echo "No match found.";
}
在做的时候:
~\bcome to\b~
不会匹配。
修改强>
// 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.";
}
要添加不区分大小写,请使用i
开关:
if (preg_match("#\b".$sentence."\b#i",$string))
答案 1 :(得分:0)
$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
}