php 系统字符串函数 截取指定长度 获取某个位置 指定截取 subtext自定义函数

 成功不了就是因为你各方面都太垃圾了,哪来那么多原因。

 

字符串截取有很多的php系统函数

 

1、sub_str()

 

substr(string $string, int $offset, ?int $length = null): string

 

$rest = substr("abcdef", 0, -1);  // 返回 "abcde"
$rest = substr("abcdef", 2, -1);  // 返回 "cde"
$rest = substr("abcdef", 4, -4);  // 返回 ""; 在 PHP 8.0.0 之前,返回 false
$rest = substr("abcdef", -3, -1); // 返回 "de"

 

2、strstr() - 查找字符串的首次出现

strstr(string $haystack, string $needle, bool $before_needle = false): string|false

举例子,注意 最后一个参数

$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com

$user = strstr($email, '@', true);
echo $user; // 打印 name

 

3、stristr() 跟strstr功能一样,只是它不区分大小写

stristr(string $haystack, string $needle, bool $before_needle = false): string|false

列举例子

$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e'); // 输出 ER@EXAMPLE.com
echo stristr($email, 'e', true); // 输出 US

 

4、strpos() - 查找字符串首次出现的位置

 

strpos(string $haystack, string $needle, int $offset = 0): int|false

 

例子

strpos('abc',  'a'); //  0 因为字符串的开始位置就是0 开始 
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0 从位置为1的字符串开始 直接忽略0

 

5、stripos() -  跟上面的一样 查找字符串首次出现的位置(不区分大小写)

应用:字符串查找首次出现的位置,然后再进行功能的输出,查看如下的案

 指定位置截取,输出

public function dada() {
  $name = '韩国游客-刘思思'; if( $positionIndex = strpos($name, '-') ) { $name = substr($name, $positionIndex+1); } echo $name;
}

 结果:

 

 

 6、strrpos() -  计算指定字符串在目标字符串中最后一次出现的位置

 

strrpos(string $haystack, string $needle, int $offset = 0): int|false

 

 

7、strripos() - 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)

 

相对上面的字符串都有对应的 多字节字符串函数

mb_substr、mb_strstr、mb_stristr、mb_strpos、mb_stripos、mb_strrpos、mb_strripos等等

 

举一个mb_strlen()  函数,长度过长,就进行截取案例

/**
 * 字符串截取
 * @param string text int length
 * @return string
 */
if (!function_exists('subtext')) {
    function subtext($text, $length, $replaceStr = '…') {
        if(mb_strlen($text, 'utf8') > $length)
            return mb_substr($text,0,$length,'utf8').$replaceStr;
        return $text;
    }
}

 

posted @ 2021-09-11 08:51  方达达  阅读(202)  评论(0编辑  收藏  举报