<?php
header("Content-Type:text/html;charset=utf-8");
#字符串处理的相关函数
#trim 该函数用于移除字符串两侧的空白字符或其他预定义字符。
#ltrim rtrim 分别用于移除左和右的空白字符。
#{参数1}字符串,{参数2}要去除的左右两面的字符串。
$str = " hello world ";
$str1 = trim($str);
echo $str1."<br />";//hello world
$str = "aaBBccaa1";
$str2 = trim($str,'aa');
echo $str2."<br />";//bbccaa1
#strtoupper 该函数用于小写转换成大写.
#strtolower 该函数用于大写转换成小写.
echo strtoupper($str)."<br />";//AABBCCAA1
echo strtolower($str)."<br />";//aabbccaa1
#substr_count 该函数用于查找字符串出现的次数。
#{参数1}:被查找的字符串
#{参数2}:查询字符串。
#{参数3}:偏移位置,索引从0开始,从左向右。
#{参数4}:结束位置,索引从0开始,从左向右。
#该函数不会重叠计算。
#strstrstr substr_count($str,'str');//1
echo substr_count($str, 'aa',0,9)."<br />";//2
#strpos 该函数用于查找字符串首次出现的位置。
#{参数1}:被查找的字符串
#{参数2}:查询字符串。
#{参数3}:偏移位置,索引从0开始,从左向右。
#{参数4}:结束位置,索引从0开始,从左向右。
echo strpos($str, 'cc');//4
#注意索引0的情况,要用全等判断。
$str = "test one day";
$result = strpos($str, 't');//此时$result的值可能为int类型的0.
if($result !== false){//判断值的同时,判断类型。
echo "找到这个字符了";
}else{
echo "没有找到这个字符";
}
echo "<br />";
#strstr 该函数用于找寻字符串是否包含子串。
#{参数1}:被查找的字符串
#{参数2}:查询字符串。
#{参数3}:boolean类型,true则表示返回查找到的子串之前的部分。默认不填写。
$str = 'abcbdefg';
$str1 = strstr($str,'cb');//字符串截取到{参数2}以后的字符串,包含{参数2}。
echo $str1."<br />";//cbdefg
$str1 = strstr($str,'cb',true);//字符串截取到{参数2}之前的字符串,不包含{参数2}。
echo $str1."<br />";//ab
#str_replace 该函数用于字符串替换
#{参数1}:查询字符串。
#{参数2}:替换的字符串。
#{参数3}:需要替换的字符串。
$str = "hello world,1 2 3 go!";
$str1 = str_replace('1', '一', $str);
echo $str1."<br />";//hello world,一 2 3 go!
#注:如涉及到此种情况,即要替换多个字符。可用数组的方式。
$str1 = str_replace(array('1','2','3'), array('one','two','three'), $str);
echo $str1."<br />";//hello world,hello world,one two three go!
#与html相关的字符串处理函数
#htmlspecialchars 该函数用于将含有html标签的字符串转义。
$str = <<<userInput
<strong style = "font-size:30px;color:red;">
hello world.hello china.
</strong>
userInput;
echo $str."<br />";//hello world.hello china.
echo htmlspecialchars($str)."<br />";//将含有html标签替换。
#strip_tags 该函数用于去除html,php的标签。
echo strip_tags($str,"<p>");//如果填写{参数2},则该标记不会被去除。
echo "<br />";
#substr 该函数用于字符串截取。
#{参数1}需要截取的字符串。
#{参数2}索引开始位置。
#{参数3}索引结束位置。
$str = "hello world";
$str1 = substr($str,0,3);//左开右关。
echo $str1."<br />";//hel
#注,可用负数作为截取开始。
$str1 = substr($str,-3);//左开右关。
echo $str1."<br />";//rld
#explode 该函数用于字符串分割
#{参数1}按照什么来切割。
#{参数2}用于切割的字符串。
#{参数3}切割的个数。
#字符串分割成数组。
$str = "one,two,three";
$str1 = explode(",",$str,3);
print_r($str1);//Array ( [0] => one [1] => two [2] => three )
echo "<br />";
#str_split 该函数用于字符串转换为数组
#{参数1}用于切割的字符串。
#{参数2}每次切割多少个字符。
print_r(str_split($str,4));//Array ( [0] => o [1] => n [2] => e...
#explode和str_split的区别.
#1、split可以用正则表达式作为分割用的标志。
#2、explode只能用某个固定的字符串作为分割标志。
#字符串函数更多应用是从手册中,需要什么就查一下用就可以了。
#盲目学习,只会更累。
?>