dongpu3792 2014-09-14 00:32
浏览 13
已采纳

如何在字符串中获取完整的子字符串?

I have variable $mystring = "abc+adb" and I am trying to find ab in the $mystring. I want to throw a message which say ab does not exist in $mystring, but the following code keeps picking ab from abc, I want ab to be treated as a standalone substring;

$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";
}
  • 写回答

1条回答 默认 最新

  • douban2014 2014-09-14 00:43
    关注

    You shouldn't use strpos for that.

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

    You can use a regular expression to do that. By no means am I a master of regular expression, but a simple example that meets your immediate need is:

    preg_match('/\bab\b/', $mystring);
    

    The preg_match function will return 1 if successful, 0 if no matches found or false in if there was an error.

    $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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题