PHP-判断字符串是否以指定字符串开头或结尾

2021-03-22 21:33 阅读:7137
    /**
     * 判断字符串是否以指定字符串开头
     * @param string $str 原字串
     * @param string $needle 开头字串
     * @return bool
     */
    public static function startWith($str, $needle) {
        return strpos($str, $needle) === 0;
    }

    /**
     * 判断字符串是否以指定字符串结尾
     * @param string $str 原字串
     * @param string $needle 结尾字串
     * @return bool
     */
    public static function endWith($str, $needle) {
        $length = strlen($needle);
        if($length == 0)
        {
            return true;
        }
        return (substr($str, -$length) === $needle);
    }

使用示例:

public function test()
{
       if (ClassName::startWith("hello", "h"))
       {
               print_r("hello word");
       }
}

文中的ClassName请替换为自己的文件类名

{{commentTotal}} 条评论

{{item.nickname}}
{{item.create_date}}
{{item.content}}
- 上拉或点击加载更多 -
- 加载中 -
- 没有更多了 -
- 本文链接 -