首页 > 语言 > PHP > 正文

php str_replace函数,可限制替换个数

2024-09-04 11:48:57
字体:大 中 小
来源:转载
供稿:网友

本文章主要是介绍str_replace函数替换单个字符,与替换数据,以及指定str_replace替换的次数,最后一个替换次数是很有用的特别是在seo优化方面.

mixed str_replace(mixed $search , mixed $replace , mixed $subject [,int &$count ] )

函数返回一个字符串或在出现问题的所有搜索给定的数组替换值替换,如果你不喜欢需要更换的规则(如正则表达式),你应该始终使用此函数,而不是ereg_replace()或preg_replace函数(),实例代码如下:

  1. */ 
  2. // provides: <body text='black'> 
  3. $bodytag = str_replace("%body%", "black", "<body text='%body%'>"); 
  4. // provides: hll wrld f php 
  5. $vowels = array("a", "e", "i", "o", "u", "a", "e", "i", "o", "u"); 
  6. $onlyconsonants = str_replace($vowels, "", "hello world of php"); 
  7. // provides: you should eat pizza, beer, and ice cream every day 
  8. $phrase  = "you should eat fruits, vegetables, and fiber every day."; 
  9. $healthy = array("fruits", "vegetables", "fiber"); 
  10. $yummy   = array("pizza", "beer", "ice cream"); 
  11. $newphrase = str_replace($healthy, $yummy, $phrase); 
  12. // provides: 2 
  13. $str = str_replace("ll", "", "good golly miss molly!", $count); 
  14. echo $count; 
  15. //利用str_replace函数指定替换次数 
  16. $array = array( 
  17.  array(0,1,2) 
  18.  ); 
  19. function keywords( $str,$array ) 
  20. { 
  21.  $count =0; 
  22.  foreach($array as $v){      
  23.   if(strstr($str,strtolower($v[0]))!==false){        
  24.    if( $count <=3 ){ 
  25.     $tos = strtolower($v[0]); 
  26.     $str=preg_replace("/$tos/","<a href=".$v[1]." target=_blank >".$v[2]."</a>",$str,1);//开源软件:Vevb.com 
  27.     $count++; 
  28.     continue; 
  29.    } 
  30.   }     
  31.  } 
  32.  return $str;   
  33. }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表