本文章主要是介紹str_replace函數替換單個字符,與替換數據,以及指定str_replace替換的次數,最后一個替換次數是很有用的特別是在seo優化方面.
mixed str_replace(mixed $search , mixed $replace , mixed $subject [,int &$count ] )
函數返回一個字符串或在出現問題的所有搜索給定的數組替換值替換,如果你不喜歡需要更換的規則(如正則表達式),你應該始終使用此函數,而不是ereg_replace()或preg_replace函數(),實例代碼如下:
- */
- // provides: <body text='black'>
- $bodytag = str_replace("%body%", "black", "<body text='%body%'>");
- // provides: hll wrld f php
- $vowels = array("a", "e", "i", "o", "u", "a", "e", "i", "o", "u");
- $onlyconsonants = str_replace($vowels, "", "hello world of php");
- // provides: you should eat pizza, beer, and ice cream every day
- $phrase = "you should eat fruits, vegetables, and fiber every day.";
- $healthy = array("fruits", "vegetables", "fiber");
- $yummy = array("pizza", "beer", "ice cream");
- $newphrase = str_replace($healthy, $yummy, $phrase);
- // provides: 2
- $str = str_replace("ll", "", "good golly miss molly!", $count);
- echo $count;
- //利用str_replace函數指定替換次數
- $array = array(
- array(0,1,2)
- );
- function keywords( $str,$array )
- {
- $count =0;
- foreach($array as $v){
- if(strstr($str,strtolower($v[0]))!==false){
- if( $count <=3 ){
- $tos = strtolower($v[0]);
- $str=preg_replace("/$tos/","<a href=".$v[1]." target=_blank >".$v[2]."</a>",$str,1);//開源軟件:Vevb.com
- $count++;
- continue;
- }
- }
- }
- return $str;
- }
新聞熱點
疑難解答