首頁  >  文章  >  後端開發  >  php數組一對一替換實現代碼一句指定兩個位置之間的字元替換為*號

php數組一對一替換實現代碼一句指定兩個位置之間的字元替換為*號

怪我咯
怪我咯原創
2017-07-10 13:54:571410瀏覽

PHP的substr_replace將指定兩個位置之間的字元替換為*號的程式碼,需要的朋友可以參考下。

程式碼如下:

$username = "zongzi"; 
echo substr_replace($username,'**','1','2');

定義和用法

substr_replace() 函數把字串的一部分替換為另一個字串。

語法

substr_replace(string,replacement,start,length)
參數 #描述
string 必需。規定要檢查的字串。
replacement 必要。規定要插入的字串。
start

必要。規定在字串的何處開始替換。

  • 正數- 在第start 個偏移量開始替換

  • 負數- 在從字串結尾的第start 個偏移量開始替換

  • 0 - 在字串中的第一個字元開始替換

charlist

可選。規定要替換多少個字元。

  • 正數- 被替換的字串長度

  • #負數- 從字串末端開始的被替換字元數

  • #0 - 插入而非替換

#提示與註解

#註解:如果start 是負數且length 小於等於start,則length 為0。
範例

 程式碼如下:

<?php 
echo substr_replace("Hello world","earth",6); 
?>

輸出:
Hello earth

以下方法可以實作配對關鍵字並分別對關鍵字做特殊處理的功能,程式碼如下

<?php 
header("Content-type: text/html; charset=utf-8"); 
function multiple_replace_words($word,$replace,$string,$tmp_match=&#39;#a_a#&#39;){ 
preg_match_all(&#39;/&#39;.$word.&#39;/&#39;,$string,$matches); //匹配所有关键词 
$search = explode(&#39;,&#39;,&#39;/&#39;.implode(&#39;/,/&#39;,$matches[0]).&#39;/&#39;); 
//不存在匹配关键词 
if(empty($matches[0])) return false; 
//特殊替换设置 
$count = count($matches[0]); 
foreach($replace as $key=>$val){ 
if(!isset($matches[0][$key])) unset($replace[$key]); //剔除越界替换 
} 
//合并特殊替换数组与匹配数组 
for($i=0;$i<$count;$i++){ 
$matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i]; 
} 
$replace = $matches[0]; 
//防止替换循环,也就是替换字符仍是被替换字符,此时将其临时替换一个特定字符$tmp_match 
$replace = implode(&#39;,&#39;,$replace); 
$replace = str_replace($word,$tmp_match,$replace); //临时替换匹配字符 
$replace = explode(&#39;,&#39;,$replace); 
//替换处理 
$string = preg_replace($search,$replace,$string,1); //每次只替换数组中的一个 
$string = str_replace($tmp_match,$word,$string); //还原临时替换的匹配字符 
return $string; 
} 
//示例1 
$string = &#39;aaabaaacaaadaaa&#39;; 
$word = &#39;aaa&#39;; 
$replace = array(null,&#39;xxx&#39;,&#39;yyy&#39;); 
echo &#39;原文:&#39;.$string.&#39;<br/>输出:&#39;.multiple_replace_words($word,$replace,$string).&#39;<br/><br/>&#39;; 
//示例2 
$string = &#39;中文aaab中文ccaaad中文eee&#39;; 
$word = &#39;中文&#39;; 
$replace = array(null,&#39;(替换中文2)&#39;,&#39;(替换中文3)&#39;); 
echo &#39;原文:&#39;.$string.&#39;<br/>输出:&#39;.multiple_replace_words($word,$replace,$string); 
/* 
输出结果: 
原文:aaabaaacaaadaaa 
输出:aaabxxxcyyydaaa 
原文:中文aaab中文ccaaad中文eee 
输出:中文aaab(替换中文2)ccaaad(替换中文3)eee 
//*/

以上是php數組一對一替換實現代碼一句指定兩個位置之間的字元替換為*號的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn