本文章主要是介紹str_replace函數(shù)替換單個字符,與替換數(shù)據(jù),以及指定str_replace替換的次數(shù),最后一個替換次數(shù)是很有用的特別是在seo優(yōu)化方面.

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

函數(shù)返回一個字符串或在出現(xiàn)問題的所有搜索給定的數(shù)組替換值替換,如果你不喜歡需要更換的規(guī)則(如正則表達式),你應(yīng)該始終使用此函數(shù),而不是ereg_replace()或preg_replace函數(shù)(),實例代碼如下:

  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函數(shù)指定替換次數(shù) 
  16. $array = array
  17.  array(0,1,2) 
  18.  ); 
  19. function keywords( $str,$array ) 
  20.  $count =0; 
  21.  foreach($array as $v){      
  22.   if(strstr($str,strtolower($v[0]))!==false){        
  23.    if$count <=3 ){ 
  24.     $tos = strtolower($v[0]); 
  25.     $str=preg_replace("/$tos/","<a >.$v[1]." target=_blank >".$v[2]."</a>",$str,1);//開源軟件:phpfensi.com 
  26.     $count++; 
  27.     continue
  28.    } 
  29.   }     
  30.  } 
  31.  return $str;   
  32. }
轉(zhuǎn)載請注明來源:php str_replace函數(shù),可限制替換個數(shù)

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無需額外費用,即可穩(wěn)步提升排名至首頁。歡迎體驗最佳的哈爾濱網(wǎng)站建設(shè)。