加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php substr_replace替换字符串一些案例

发布时间:2023-11-13 16:51:45 所属栏目:PHP教程 来源:
导读:substr_replace() 函数把字符串的一部分替换为另一个字符串。

用法

substr_replace(string,replacement,start,length)

注意当字符串包含中文时,不经过特殊处理会出现乱码。

代码如下

1

$s
substr_replace() 函数把字符串的一部分替换为另一个字符串。
 
用法
 
substr_replace(string,replacement,start,length)
 
注意当字符串包含中文时,不经过特殊处理会出现乱码。
 
 代码如下
 
1
 
$string1="123456789";   

echo substr_replace($string1,'###',0);
 
//###
 
echo substr_replace($string1,'###',5);
 
//12345###   
 
echo substr_replace($string1,'###',0,0);
 
//###123456789

echo substr_replace($string1,'###',8,-2);
 
//12345678###9
 
echo substr_replace($string1,'###',-6,-1);
 
//123###9
 
echo "n";
 
echo substr_replace($string1,'###',-1);
 
//123###9
 
echo "n";
 
echo substr_replace($string1,'###',1,-1);
 
//1###9
 
echo substr_replace($string1,'###',1,1);
 
//1###3456789
 
?>
 
例2

 代码如下
 
1
 
 $var = 'ABCDEFGH:/MNRPQR/';
 
 echo "Original: $var
 
n";
 
 /* These two examples replace all of $var with 'bob'. */
 
 echo substr_replace($var, 'bob', 0) . "
 
n";
 
 echo substr_replace($var, 'bob', 0, strlen($var)) . "
 
n";
 
 /* Insert 'bob' right at the beginning of $var. */
 
 echo substr_replace($var, 'bob', 0, 0) . "
 
n";
 
 /* These next two replace 'MNRPQR' in $var with 'bob'. */
 
 echo substr_replace($var, 'bob', 10, -1) . "
 
n";
 
 echo substr_replace($var, 'bob', -7, -1) . "
 
n";
 
 /* Delete 'MNRPQR' from $var. */
 
 echo substr_replace($var, '', 10, -1) . "
 
n";
 
?>
 
Original: ABCDEFGH:/MNRPQR/
 
bob
 
bob
 
bobABCDEFGH:/MNRPQR/
 
ABCDEFGH:/bob/
 
ABCDEFGH:/bob/
 
ABCDEFGH://
 
将过长的字符串用省略号代替一部分
 
下面的程序可以将过长的字符串保留首尾,中间用省略号代替。
 
 代码如下
 
1
 
 $longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
 
 $separator = '...';
 
 $separatorlength = strlen($separator) ;
 
    // 需要保留的字符串
 
 $maxlength = 25 - $separatorlength;
 
    // 从一半的长度开始
 
 $start = $maxlength / 2 ;
 
    // 计算偏移量
 
 $trunc =  strlen($longString) - $maxlength;
 
 echo substr_replace($longString, $separator, $start, $trunc);
 
 //prints "abcdefghij...56789z.jpg"
 
?>
 
程序运行结果:
 
abcdefghijk...456789z.jpg
 
Program List:将多出的字符用省略号代替
 
 代码如下
 
1   
 
 
function truncate($text,$numb)
 
{
 
 $text = html_entity_decode($text, ENT_QUOTES);
 
 if (strlen($text) > $numb)
 
 {
 
  $text = substr($text, 0, $numb);
 
  $text = substr($text,0,strrpos($text," "));
 
     //This strips the full stop:
 
     if ((substr($text, -1)) == ".")
 
  {
 
         $text = substr($text,0,(strrpos($text,".")));
 
     }
 
  $etc = "...";
 
  $text = $text.$etc;
 
 }
 
 $text = htmlentities($text, ENT_QUOTES);
 
 return $text;
 
}
 
//Call function
 
$text = 'welcome to nowamagic, welcome to nowamagic, welcome to nowamagic';
 
$result = truncate($text, 35);
 
echo $result;
 
?>
 
好了你大概会知道此函数的作用了。
 
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章