php字符串的替換,分割和連接方法

字號:


    本文實例講述了php字符串的替換,分割和連接方法。分享給大家供大家參考,具體如下:
    字符串的替換
    1. 執(zhí)行一個正則表達式的搜索和替換
    復制代碼 代碼如下:
    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 ] )
    該函數(shù)返回一個字符串或者數(shù)組。該字符串或數(shù)組是將 subject 中全部的 search 都被 replace 替換之后的結(jié)果。
    字符串的分割和連接
    通過一個正則表達式分隔字符串
    說明
    1. array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
    通過一個正則表達式分隔給定字符串.
    2. explode — 使用一個字符串分割另一個字符串
    說明:
    array explode ( string $separator , string $string [, int $limit ] )
    $str = 'one|two|three|four';
    // 正數(shù)的 limit
    print_r(explode('|', $str, 2));
    // 負數(shù)的 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) ———— 連接數(shù)組稱為字符串
    $lan=array("a","b","c");
    implode("+", $lan);//a+b+c
    希望本文所述對大家PHP程序設計有所幫助。