PHP字符串开头和结尾的判断方法

简介: PHP字符串开头和结尾的判断方法

1、知识准备

// 计算字符串长度
echo strlen("hello") . PHP_EOL;
// 5
// 截取字符串
echo substr("hello world!", 6, 5) . PHP_EOL;
// world
// 查找子串起始位置
echo strpos("hello world!", "world"). PHP_EOL;
// 6

2、字符串开头结尾判断

//变量:
$s1 = "hello";
$s2 = "hello world!";
$s3 = "world hello";
//php判断字符串开头:
var_dump(substr($s2, 0, strlen($s1)) === $s1); 
// bool(true)
var_dump(strpos($s2, $s1) === 0);
// bool(true)
//php判断字符串结尾:
var_dump(substr($s3, strpos($s3, $s1)) === $s1);
// bool(true)

3、函数封装

<?php
/**
 * 字符串工具类
 */
class StringUtil{
    public static function startsWith(string $string, string $subString) : bool{
        return substr($string, 0, strlen($subString)) === $subString;
        // 或者 strpos($s2, $s1) === 0
    }
    public static function endsWith(string $string, string $subString) : bool{
        return substr($string, strpos($string, $subString)) === $subString;
    }
}

测试代码

var_dump(StringUtil::startsWith('hello world', 'hello'));
// bool(true)
var_dump(StringUtil::startsWith('hello world', 'world'));
// bool(false)
var_dump(StringUtil::endsWith('hello world', 'hello'));
// bool(false)
var_dump(StringUtil::endsWith('hello world', 'world'));
// bool(true)
相关文章
|
23天前
|
缓存 PHP 开发者
PHP中的自动加载机制及其优化方法
传统的PHP开发中,经常会遇到类文件加载繁琐、效率低下的情况,而PHP的自动加载机制能够很好地解决这一问题。本文将深入探讨PHP中的自动加载机制,介绍其原理及实现方式,并提出了一些优化方法,帮助开发者提升代码加载效率,提高应用性能。
|
1月前
|
SQL 缓存 PHP
PHP技术探究:优化数据库查询效率的实用方法
本文将深入探讨PHP中优化数据库查询效率的实用方法,包括索引优化、SQL语句优化以及缓存机制的应用。通过合理的优化策略和技巧,可以显著提升系统性能,提高用户体验,是PHP开发者不容忽视的重要议题。
|
3天前
|
存储 SQL 缓存
记录如何用php做一个网站访问计数器的方法
创建简单网站访问计数器,可通过存储访问次数的文件或数据库。首先,创建`counter.txt`存储计数,然后在`counter.php`中编写PHP代码以读取、增加并显示计数,使用`flock`锁定文件避免并发问题。网页通过包含`counter.php`展示计数。对于高流量网站,推荐使用数据库确保原子性和并发处理能力,或利用缓存提升性能。注意,实际生产环境可能需更复杂技术防止作弊。
|
1月前
|
JSON JavaScript PHP
PHP把unicode编码的json字符串转中文
PHP把unicode编码的json字符串转中文
13 0