這篇文章主要介紹了php字串的替換,分割和串連方法,分析了preg_replace、str_replace、preg_split、explode及implode等函數的功能與使用方法,需要的朋友可以參考下
字串的替換
1. 執行一個Regex的搜尋和替換
代碼如下:
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
搜尋subject中匹配pattern的部分, 以replacement進行替換.
2. 子字串替換
代碼如下:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
該函數返回一個字串或者數組。該字串或數組是將 subject 中全部的 search 都被 replace 替換之後的結果。
字串的分割和串連
通過一個Regex分隔字串
說明
1. array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
通過一個Regex分隔給定字串.
2. explode — 使用一個字串分割另一個字串
說明:
array explode ( string $separator , string $string [, int $limit ] )
$str = 'one|two|three|four';// 正數的 limitprint_r(explode('|', $str, 2));// 負數的 limit(自 PHP 5.1 起)print_r(explode('|', $str, -1));
以上常式會輸出:
Array( [0] => one [1] => two|three|four)Array( [0] => one [1] => two [2] => three)
3. string implode(string glue, array pieces) ———— 串連數組稱為字串
$lan=array("a","b","c");implode("+", $lan);//a+b+c
總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。