php substr_replace替换字符串一些实例

substr_replace与str_replace有一点像就是直接把字符串替换一部份了,下面小编来给各位同学介绍一下操作方法。

substr_replace() 函数把字符串的一部分替换为另一个字符串。

用法:

substr_replace(string,replacement,start,length)

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

  1. <?php
  2. $string1="123456789";
  3. echo substr_replace($string1,'###',0);
  4. //###
  5. echo substr_replace($string1,'###',5);
  6. //12345###
  7. echo substr_replace($string1,'###',0,0);
  8. //###123456789
  9. echo substr_replace($string1,'###',8,-2);
  10. //12345678###9
  11. echo substr_replace($string1,'###',-6,-1);
  12. //123###9
  13. echo "n";
  14. echo substr_replace($string1,'###',-1);
  15. //123###9
  16. echo "n";
  17. echo substr_replace($string1,'###',1,-1);
  18. //1###9
  19. echo substr_replace($string1,'###',1,1);
  20. //1###3456789
  21. ?>

例2代码如下:

  1. <?php
  2. $var = 'ABCDEFGH:/MNRPQR/';
  3. echo "Original: $var<hr />n";
  4. /* These two examples replace all of $var with 'bob'. */
  5. echo substr_replace($var, 'bob', 0) . "<br />n";
  6. echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />n";
  7. /* Insert 'bob' right at the beginning of $var. */
  8. echo substr_replace($var, 'bob', 0, 0) . "<br />n";
  9. /* These next two replace 'MNRPQR' in $var with 'bob'. */
  10. echo substr_replace($var, 'bob', 10, -1) . "<br />n";
  11. echo substr_replace($var, 'bob', -7, -1) . "<br />n";
  12. /* Delete 'MNRPQR' from $var. */
  13. echo substr_replace($var, '', 10, -1) . "<br />n";
  14. ?>

将过长的字符串用省略号代替一部分,下面的程序可以将过长的字符串保留首尾,中间用省略号代替,代码如下:

  1. <?php
  2. $longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
  3. $separator = '...';
  4. $separatorlength = strlen($separator) ;
  5. // 需要保留的字符串
  6. $maxlength = 25 - $separatorlength;
  7. // 从一半的长度开始
  8. $start = $maxlength / 2 ;
  9. // 计算偏移量
  10. $trunc = strlen($longString) - $maxlength;
  11. echo substr_replace($longString, $separator, $start, $trunc);
  12. //prints "abcdefghij...56789z.jpg"
  13. ?>
  14. //程序运行结果:
  15. //abcdefghijk...456789z.jpg

Program List:将多出的字符用省略号代替,代码如下:

  1. <?php
  2. function truncate($text,$numb)
  3. {
  4. $text = html_entity_decode($text, ENT_QUOTES);
  5. if (strlen($text) > $numb)
  6. {
  7. $text = substr($text, 0, $numb);
  8. $text = substr($text,0,strrpos($text," "));
  9. //This strips the full stop:
  10. if ((substr($text, -1)) == ".")
  11. {
  12. $text = substr($text,0,(strrpos($text,".")));
  13. }
  14. $etc = "...";
  15. $text = $text.$etc;
  16. }
  17. $text = htmlentities($text, ENT_QUOTES);
  18. return $text;
  19. }
  20. //Call function
  21. $text = 'welcome to nowamagic, welcome to nowamagic, welcome to nowamagic';
  22. $result = truncate($text, 35);
  23. echo $result;
  24. ?>

好了你大概会知道此函数的作用了.