比如有一個字串:$a=’hello world hello pig hello cat hello dog hello small boy’;
然後想將第3次出現的hello 改變成為good-bye,比如:
‘hello world hello pig good-bye cat hello dog hello small boy’;
這樣的情況,我一時半會沒找到PHP的內建函數,而且在要求不能使用Regex的情況下,就編寫了這個簡易的小函數,如果大家有好的內建函數推薦,歡迎留言:)
| 代碼如下 |
複製代碼 |
<?php /* * $text是輸入的文本; * $word是原來的字串; * $cword是需要替換成為的字串; * $pos是指$word在$text中第N次出現的位置,從1開始算起 * */ function changeNstr($text,$word,$cword,$pos=1){ $text_array=explode($word,$text); $num=count($text_array)-1; if($pos>$num){ return "the number is too big!or can not find the $word"; } $result_str=''; for($i=0;$i<=$num;$i++){ if($i==$pos-1){ $result_str.=$text_array[$i].$cword; }else{ $result_str.=$text_array[$i].$word; } } return rtrim($result_str,$word); } $text='hello world hello pig hello cat hello dog hello small boy'; $word='hello'; $cword='good-bye'; echo changeNstr($text,$word,$cword,3); //輸出:hello world hello pig good-bye cat hello dog hello small boy ?> |
正則會更方法
如果是utf-8編碼的話
| 代碼如下 |
複製代碼 |
<?php $regex = "/(,|,||||)/i"; $test = "河北,石家莊,北京,上海|天津|||重慶|保定,,,河南, "; $result = preg_replace($regex," ",$test); print_r($result); ?> |
結果
河北 石家莊 北京 上海 天津 重慶 保定 河南
php函數替換
PHP常用正則匹配函數間的區別,主要有str_replace、str_ireplace、substr_replace、preg_replace、preg_match、preg_match_all、preg_quote、preg_split、ereg_replace、eregi_replace、preg_replace、str_split,當然其中有幾個不能使用Regex,但因為跟相關正則函數關係曖昧所以都放到一起比較一下
| |
支援正則 |
特點 |
備忘 |
| str_replace |
X |
字串替換函數,大小寫敏感 |
|
| str_ireplace |
X |
字串替換函數,大小寫不敏感,支援數組式批量替換 |
感謝網友franci,提醒添加 |
| substr_replace |
X |
部分替換字串函數,可以指定位置index |
|
| |
|
|
|
| preg_replace |
Y |
指定匹配模式進行替換,支援子串引用 |
優先使用 |
| ereg_replace |
Y |
指定匹配模式進行替換,大小寫敏感,支援子串引用 |
|
| eregi_replace |
Y |
指定匹配模式進行替換,大小寫不敏感,支援子串引用 |
|
| |
|
|
|
| ereg |
Y |
指定模式全文匹配,可以用來匹配判斷,或返回匹配數組 |
|
| preg_match |
Y |
指定模式比對一次退出,可以用來是否匹配判斷,或使用返回的匹配數組 |
優先使用 |
| preg_match_all |
Y |
指定模式全文匹配,一般用來使用返回的匹配數組 |
優先使用 |
| |
|
|
|
| preg_split |
Y |
指定匹配模式下正則剖分,如果能用最好還是使用explode或str_split |
|
| str_split |
X |
指定長度剖分字串,預設單個字元剖分成數組 |
|
| explode |
X |
可以指定單個或多個字元剖分字串,成功則返回數組,例如12345按照34剖分則返回12和5 |
|
| |
|
|
|
| preg_quote |
- |
轉義Regex字元,意思就是為特殊字元加上反斜線,Regex的特殊字元包括:. + * ? [ ^ ] $ ( ) { } = ! < > | : - |
|
| |
|
|
|