分类分类
更新时间:2026-05-10 22:20:02作者:sa
substr_replace与str_replace有一点像就是直接把字符串替换一部份了,下面小编来给各位同学介绍一下操作方法。
substr_replace() 函数把字符串的一部分替换为另一个字符串。
用法:
substr_replace(string,replacement,start,length)
注意当字符串包含中文时,不经过特殊处理会出现乱码,代码如下:
<?php
$string1="123456789";
echo substr_replace($string1,'###',0);
//### http://www.bcty365.com
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代码如下:
<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />n";
/* These two examples replace all of $var with 'bob'.
*/http://www.bcty365.com
echo substr_replace($var, 'bob', 0) . "<br />n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />n";
/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />n";
/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />n";
echo substr_replace($var, 'bob', -7, -1) . "<br />n";
/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />n";
?>
将过长的字符串用省略号代替一部分,下面的程序可以将过长的字符串保留首尾,中间用省略号代替,代码如下:
<?php
$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '...';
$separatorlength = strlen($separator) ;
// 需要保留的字符串
$maxlength = 25 - $separatorlength;
// 从一半的长度开始http://www.bcty365.com
$start = $maxlength / 2 ;
// 计算偏移量
$trunc = strlen($longString) - $maxlength;
echo substr_replace($longString, $separator, $start, $trunc);
//prints "abcdefghij...56789z.jpg"
?>
//程序运行结果:
//abcdefghijk...456789z.jpg
Program List:将多出的字符用省略号代替,代码如下:
<?php
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;
?>
好了你大概会知道此函数的作用了.
相关
修真情缘角色扮演303.33 MBv1.0.02026-05-10
下载我的小独角兽女孩休闲益智380.89 MBv1.0.232026-05-10
下载超级种田男孩手机版经营养成1.31Gv1.0.92026-05-10
下载不必要的实验冒险游戏64.9 MBv1.1.592026-05-10
下载军师联盟策略游戏163.2 MBv0.0.12026-05-10
下载翻天喜地凑大钱手机版休闲益智138.72 MBv1.0.92026-05-10
下载东离剑游纪手游动作射击1.6Gv1.4.22026-05-10
下载天猫养车商家版App学习办公74.95 MBv0.6.12026-05-10
下载掌上命运方舟App手游辅助137.48 MBv1.9.12026-05-10
下载退役军人服务APP生活服务67.16 MBv1.2.52026-05-10
下载屯漫漫画APP资讯阅读23.06 MBv2.0.32026-05-10
下载蛋仔派对蛋壳App手游辅助185.73 MBv0.0.22026-05-10
下载









