What are the methods for intercepting strings in php

藏色散人
Release: 2023-03-08 18:50:01
Original
14201 people have browsed it

php截取字符串方法有:1、使用substr函数截取字符串;2、使用mb_substr函数截取字符串;3、使用自定义的“function mysubstr($str, $start, $len){}”方法截取字符串等等。

What are the methods for intercepting strings in php

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php截取字符串几个实用的函数

1.substr(源字符串,其实位置[,长度])-截取字符串返回部分字符串

Copy after login

但是当你截取中文字符串的时候很容易出现乱码,因为一个汉字是两个字节,而一个英文字母是一个字节。解决办法如下:

2.mb_substr(),使用方法和substr相同,不过要开启php.ini里面extension=php_mbstring.dll扩展,不用担心,一般的空间商都会开启这个扩展的。

Copy after login

代码如下:

substr(string,start,length)
Copy after login

其中start的参数

正数 - 在字符串的指定位置开始

负数 - 在从字符串结尾的指定位置开始

0 - 在字符串中的第一个字符处开始

******************************************************************

strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。

该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。

strstr('abc@jb51.net', '@', TRUE); //参数设定true, 返回查找值@之前的首部,abc
strstr( 'abc@jb51.net', '@'); //默认返回查找值@之后的尾部,@jb51.net
Copy after login

网上也有很多中文字符串截取教程,实现起来比较复杂,感觉还是用php自带的函数实现起来比较好。整理的网络资料(php代码)如下:

(1)截取GB2312中文字符串

0xa0){
$tmpstr .= substr($str, $i,2);
$i++;
}else
$tmpstr .= substr($str, $i,1);
}
return $tmpstr;
}
echo mysubstr("php点点通",1,5);//php点
?>
Copy after login

(2)截取utf8编码的多字节字符串

Copy after login

(3)支持 utf-8、gb2312都支持的汉字截取函数

 $sublen)return join('', array_slice($t_string[0], $start, $sublen))."...";
return join('', array_slice($t_string[0], $start, $sublen));
}
else
{
$start = $start*2;
$sublen = $sublen*2;
$strlen = strlen($string);
$tmpstr ='';for($i=0; $i<$strlen; $i++)
{
if($i>=$start && $i<($start+$sublen))
{
if(ord(substr($string, $i,1))>129)
{
$tmpstr.= substr($string, $i,2);
}
else
{
$tmpstr.= substr($string, $i,1);
}
}
if(ord(substr($string, $i,1))>129) $i++;
}
if(strlen($tmpstr)<$strlen ) $tmpstr.="...";
return $tmpstr;
}
}
$str ="php点点通提供原创php教程";
echo cut_str($str,8,0);//php点点通提供...
?>
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of What are the methods for intercepting strings in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!