php 字符串替換函數(shù)
來源:程序員人生 發(fā)布時(shí)間:2014-03-15 15:25:41 閱讀次數(shù):3066次
本文章給php初學(xué)者講了兩個(gè)php中實(shí)例的字符替換函數(shù),一個(gè)是str_ireplace()一個(gè)是substr_replace()這兩個(gè)函數(shù)都比較好用,有需要的參考一下。
字符串的替換技術(shù)可以通過以下兩個(gè)常用函數(shù)實(shí)現(xiàn):str_ireplace()函數(shù)和substr_replace()函數(shù)
str_ireplace()函數(shù)
使用新的子字符串替換原始字符串中被指定要替換的字符串,語法:
mixed str_ireplace(mixed search,mixed replace,mixed subject[,int&count])
參數(shù)search:必要參數(shù),指定需要查找的字符串。
參數(shù)replace:必要參數(shù),指定替換的值。
參數(shù)subject:必要參數(shù),指定查找的范圍。
參數(shù)count:可選參數(shù),(帶中括號(hào)的為可選參數(shù)),獲取執(zhí)行替換的數(shù)量。
實(shí)例代碼如下:
- <?php
- $str2=”某某”;
- $str1=”**”;
- $str=”某某網(wǎng)站的地址是www.phpfensi.com ,某某網(wǎng)站主要記錄一些學(xué)習(xí)php的筆記和感想以及各種軟件知識(shí)”;
- echo str_ireplace($str2,$str1,$str);
- ?>
在本例中,我們將演示帶有數(shù)組和count變量的 str_ireplace()函數(shù),代碼如下:
- <?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()函數(shù)
對(duì)指定字符串中的部分字符串進(jìn)行替換,語法:
string substr_replace(string str,string repl,int start,[int length])
參數(shù)str:指定要操作的原始字符串。
參數(shù)repl:必要參數(shù),指定替換后的新字符串。
參數(shù)start:指定替換字符串開始的位置。
參數(shù)length:指定返回的字符串長度。
實(shí)例代碼如下:
- <?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);
- ?>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)