php 字符串替換函數
來源:程序員人生 發布時間:2014-03-15 15:25:41 閱讀次數:3071次
本文章給php初學者講了兩個php中實例的字符替換函數,一個是str_ireplace()一個是substr_replace()這兩個函數都比較好用,有需要的參考一下。
字符串的替換技術可以通過以下兩個常用函數實現:str_ireplace()函數和substr_replace()函數
str_ireplace()函數
使用新的子字符串替換原始字符串中被指定要替換的字符串,語法:
mixed str_ireplace(mixed search,mixed replace,mixed subject[,int&count])
參數search:必要參數,指定需要查找的字符串。
參數replace:必要參數,指定替換的值。
參數subject:必要參數,指定查找的范圍。
參數count:可選參數,(帶中括號的為可選參數),獲取執行替換的數量。
實例代碼如下:
- <?php
- $str2=”某某”;
- $str1=”**”;
- $str=”某某網站的地址是www.phpfensi.com ,某某網站主要記錄一些學習php的筆記和感想以及各種軟件知識”;
- echo str_ireplace($str2,$str1,$str);
- ?>
在本例中,我們將演示帶有數組和count變量的 str_ireplace()函數,代碼如下:
- <?php
- $arr = array("blue","red","green","yellow");
- print_r(str_ireplace("red","pink",$arr,$i));
- echo "Replacements: $i";
- ?>
-
- Array
- (
- [0] => blue
- [1] => pink
- [2] => green
- [3] => yellow
- )
Replacements:1例子3,代碼如下:
- <?php
- $find = array("Hello","world");
- $replace = array("B");
- $arr = array("Hello","world","!");
- print_r(str_ireplace($find,$replace,$arr));
- ?>
-
- Array
- (
- [0] => B
- [1] =>
- [2] => !
- )
substr_replace()函數
對指定字符串中的部分字符串進行替換,語法:
string substr_replace(string str,string repl,int start,[int length])
參數str:指定要操作的原始字符串。
參數repl:必要參數,指定替換后的新字符串。
參數start:指定替換字符串開始的位置。
參數length:指定返回的字符串長度。
實例代碼如下:
- <?php
- substr_replace('eggs','x',-1,-1);
- substr_replace('eggs','x',-1,-2);
- substr_replace('eggs','x',-1,-2);
- ?> Same as:
- <?php
- substr_replace('eggs','x',-1,0);
- ?>
- <?php
- substr_replace('huevos','x',-2,-2);
- substr_replace('huevos','x',-2,-3);
- substr_replace('huevos','x',-2,-3);
- ?> Same as:
- <?php
- substr_replace('huevos','x',-2,0);
- ?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈