Blogger Information
Blog 48
fans 3
comment 1
visits 36986
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
字符串函数的使用——2018年4月18日
JackBlog
Original
565 people have browsed it

一、字符串长度获取

1、strlen($str):获取字节表示的字符串长度。

2、mb_strlen($str, $encoding):获取字符数表示的长度

二、字符串分割

1、str_split(string,length):把字符串分割到数组中。

2、explode(separator,string,limit):把字符串打散为数组。

3、implode(separator,array):返回由数组元素组合成的字符串。

三、字符串查找及替换

1、strpos(string,find,start):查找字符串在另一字符串中第一次出现的位置。

2、strstr(string,search,before_search):搜索字符串在另一字符串中的第一次出现,并返回字符串的剩余部分。

3、str_replace(find,replace,string,count):以其他字符替换字符串中的一些字符(区分大小写)。

4、substr_replace(string,replacement,start,length):把字符串的一部分替换为另一个字符串。

2.png

实例

<?php 
echo '<h2 style="color:red">取字符串长度</h2>';
$str = '钓鱼岛是中国的';
//strlen($str)
echo strlen($str);
echo '<br>';
//mb_strlen
echo mb_strlen($str);

echo '<hr><h2 style="color:red">字符串分割</h2>';
//字符串分割
//
// $number = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27';
for ($i=0; $i < 28; $i++) { 
	$number .= $i < 27 ? $i.',' : $i;
}

//1、str_split(str,length) 第二个参数length默认为1
$arr1 = str_split($number);
echo '<p style="color:blue">str_split(str,length):</p>';
print_r($arr1);
echo '<br><br><br>';
$arr1 = str_split($number,3);

print_r($arr1);
// 2、explode(delimiter, string, num) 
echo '<br><br><br>';
$arr2 = explode(',', $number);
echo '<p style="color:blue">explode(delimiter, string, num):</p>';
print_r($arr2);

//3、implode(glue, pieces)

$str = implode('|', $arr2);
echo '<p style="color:blue">explode(delimiter, string, num):</p>';
echo $str;

echo "<hr>";
echo '<h2 style="color:red">字符串的查找与替换</h2>';
$str = 'php新人,多多关照!';
//1.strpos($str,$needle, $offset)查找字符串在另一字符串中第一次出现的位置。
echo '逗号“,”在第'.strpos($str, ',').'位<br>'; 
//2.strstr($str1, $str2),查找字符串在另一字符串中的第一次出现,并返回字符串的剩余部分.

echo strstr($str, '新人').'<br>';//返回查询的字符串和后边部分。
echo strstr($str, '新人',true).'<br>';//如果第三个参数为true,则只返回前边部分。

//3.str_replace($str1, $str2, $str3, $num):替换字符串中的一些字符

echo str_replace('php', 'php,css,js', $str).'<br>';//参数一:查询的字符串。参数二:替换的字符串。参数三:目标字符串

//4.substr_replace($str1,$str2,$str3,$start, $length):把字符串的一部分替换为另一个字符串。
echo substr_replace($str, 'php,css,js', 0,3);

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!