dongpu3792 2014-09-13 16: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-13 16: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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部