heredoc、nowdoc
<?php
//heredoc功能与双引号类似,字符串内部不需要添加定界符
$str=<<<heredoc
this is "heredoc '
heredoc;
echo $str,'<br>';
$a=<<<a
12345{$str}54321
a;
echo $a,'<br>';
//nowdoc功能和单引号类似,字符串内部不需要添加定界符
echo <<<nowdoc
this is nowdoc\ '
nowdoc;
字符串、数组的转换
imlpode,将数组转化为字符串, implode(‘分隔符’,\$arr),返回字符串
explode,字符串转化为数组 explode(‘分隔符’,\$arr,子串数),返回数组
//implode,数组转为字符串
$arr=['aaa','bbb','ccc'];
echo implode('-',$arr);
//explode字符串转化为数组
$str='123-456-789';
printf('<pre>%s</pre>',print_r(explode('-',$str),true));
//将字符串分成两部分取出
printf('<pre>%s</pre>',print_r(explode('-',$str,2),true));
字符串分割替换
- 按位替换子串 substr_replace($arr,子串,$start,\$length),返回字符串或数组
//替换字符串中的子串
//从第四位替换三位
echo substr_replace('123456789','abc',3,3);
//替换字符串
echo substr_replace('123456789','abc',0);
//插入字符串
echo substr_replace('123456789','abc',0,0);
//替换最后一位
echo substr_replace('123456789','abc',-1);
//替换数组
printf('<pre>%s</pre>',print_r(substr_replace(['a:1','b:2','c:3'],['a','b','c'],2,1),true));
- 按子串内容替换 str_replace(查询,替换,$arr,$count 记录替换次数),查询和替换内容可以用数组表示,返回字符串
//str_replace()
echo str_replace('111','XXX','111222333222111',$count),"替换了{$count}次<br>";
echo str_replace(['111','333'],'XXX','111222333222111',$count),"替换了{$count}次<br>";
echo str_replace(['111','333'],['XXX','√√√'],'111222333222111',$count),"替换了{$count}次";
- chunk_split($str,$number 每段字符数) 分割字符串
echo var_export(chunk_split('123456789',2),true);
查询字符串
- strstr(\$str,子串,\$before_search)查询字符串是否存在子串
echo var_export(chunk_split('123456789',2),true),'<br>';
//返回值为字符串中56前面的内容
echo strstr('123456789','56',true),'<br>';
//返回值为字符串56后面的内容
echo strstr('123456789','56'),'<br>';
//搜索不到子串时返回null
var_dump(strstr('123456789','aaa')) ;
- substr_count($arr,$子串)查询子串出现次数
//查询子串12出现次数
echo substr_count('123456543212','12');
//从第二位开始查询
echo substr_count('123456543212','12',1);
//从最后两位查询
echo substr_count('123456543212','12',-2,2);
- strlen()查询字符串长度
- trim()移除字符串两边的字符
$str=' 123456';
echo strlen($str);
echo strlen(trim($str));
echo strlen(rtrim($str,'56'));
总结:常用的字符串函数比较多,需要多加练习,以函数名,参数,返回值这三方面进行记忆