我有变量$mystring = "abc+adb"
,我试图在$mystring
中找到ab。我想抛出一条消息,说$mystring
中不存在ab,但是下面的代码一直在从abc中选择ab,我希望ab被视为一个独立的子字符串;
$mystring = 'abc+adb';
$findme = 'bc';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
}
else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
答案 0 :(得分:1)
你不应该使用strpos。
strpos - 查找字符串
中第一次出现子字符串的位置您可以使用正则表达式来执行此操作。我绝不是正则表达的大师,但是满足您当前需求的简单示例是:
preg_match('/\bab\b/', $mystring);
如果成功,preg_match函数将返回1,如果未找到匹配则返回0,如果出现错误则返回false。
$mystring = 'abc+adb';
$findme = 'bc';
if ( preg_match('/\b' . $findme . '\b/',$mystring) ) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
$pos = strpos($mystring, $findme);
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}