php对字符串的操作2之 处理字符串的内置函数

1,获取字串:substr($str,$start,$length)

<?php
$email = '[email protected]';
echo '原始字符串:'.$email; echo '<hr>';
//从0角标开始,获取7个字符
echo substr($email,0,7);echo '<hr>';
//-3:负数表示从末尾往前数
echo substr($email,-3,3);echo '<hr>';
?>

2,替换字串:substr_replace()

<?php
$email = '[email protected]';
echo '原始字符串:'.$email; echo '<hr>';
//注意,从负数和正数不同,负数是从-1开始数,正数从0开始
echo substr_replace($email,'163',9,2);echo '<hr>';
echo substr_replace($email,'cn',-3,3);echo '<hr>';

//将字串长度设置为0,实现无删除的插入
echo substr_replace($email,'_zhu',8,0);echo '<hr>';
//设置空字串,是实现插入式的删除
echo substr_replace($email, '', 0,4);echo '<hr>';
//在起始位置插入字符
echo substr_replace($email, '我的邮箱:', 0,0);echo '<hr>';
?>

3,substr_count():查询字串出现的频率(次数)  

<?php
$email = 'My blog name is cl94,welcome to my blog';
echo '原始字符串:'.$email; echo '<hr>';
echo substr_count($email,'blog',0,10); echo '<hr>';
?>

4,substr_compare($str,$str1,startpos):比较字串

<?php
$str1 = 'My blog name is cl94,welcome to my blog';
$str2 = 'My blog';
//startpos:规定在 string1 中的何处开始比较。如果为负数,则从字符串末端开始计数。
//返回结果 (0:相等;<0:$str1<$str2; >0:$str1>$str2);
//比较的是ascii值
echo substr_compare($str1, $str2,0); echo '<hr>';

echo substr_compare($str1, $str2,0,7);echo '<hr>';

?>

猜你喜欢

转载自www.cnblogs.com/cl94/p/9013685.html
今日推荐