php substr_replace替换字符串一些实例
来源:程序员人生 发布时间:2013-10-28 06:31:30 阅读次数:3416次
substr_replace与str_replace有一点像就是直接把字符串替换一部份了,下面小编来给各位同学介绍一下操作方法。
substr_replace() 函数把字符串的一部分替换为另一个字符串。
用法:
substr_replace(string,replacement,start,length)
注意当字符串包含中文时,不经过特殊处理会出现乱码,代码如下:
- <?php
- $string1="123456789";
-
- echo substr_replace($string1,'###',0);
-
- echo substr_replace($string1,'###',5);
-
-
- echo substr_replace($string1,'###',0,0);
-
-
- echo substr_replace($string1,'###',8,-2);
-
-
- echo substr_replace($string1,'###',-6,-1);
-
- echo "n";
- echo substr_replace($string1,'###',-1);
-
- echo "n";
- echo substr_replace($string1,'###',1,-1);
-
-
- echo substr_replace($string1,'###',1,1);
-
- ?>
例2代码如下:
- <?php
- $var = 'ABCDEFGH:/MNRPQR/';
- echo "Original: $var<hr />n";
-
- echo substr_replace($var, 'bob', 0) . "<br />n";
- echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />n";
-
- echo substr_replace($var, 'bob', 0, 0) . "<br />n";
-
- echo substr_replace($var, 'bob', 10, -1) . "<br />n";
- echo substr_replace($var, 'bob', -7, -1) . "<br />n";
-
- echo substr_replace($var, '', 10, -1) . "<br />n";
- ?>
将过长的字符串用省略号代替一部分,下面的程序可以将过长的字符串保留首尾,中间用省略号代替,代码如下:
- <?php
- $longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
- $separator = '...';
- $separatorlength = strlen($separator) ;
-
- $maxlength = 25 - $separatorlength;
-
- $start = $maxlength / 2 ;
-
- $trunc = strlen($longString) - $maxlength;
- echo substr_replace($longString, $separator, $start, $trunc);
-
- ?>
-
-
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," "));
-
- if ((substr($text, -1)) == ".")
- {
- $text = substr($text,0,(strrpos($text,".")));
- }
- $etc = "...";
- $text = $text.$etc;
- }
- $text = htmlentities($text, ENT_QUOTES);
- return $text;
- }
-
- $text = 'welcome to nowamagic, welcome to nowamagic, welcome to nowamagic';
- $result = truncate($text, 35);
- echo $result;
- ?>
好了你大概会知道此函数的作用了.
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠