php中preg_replace_callback函數(shù)簡單用法示例

字號:


    本文實例講述了php中preg_replace_callback函數(shù)用法。分享給大家供大家參考,具體如下:
    mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit] )
    本函數(shù)的行為幾乎和 preg_replace() 一樣,除了不是提供一個 replacement 參數(shù),而是指定一個 callback 函數(shù)。該函數(shù)將以目標字符串中的匹配數(shù)組作為輸入?yún)?shù),并返回用于替換的字符串。
    例如問題:
    preg_replace($skx,$imsz2,$neirong);
    如:$neirong中有多個$skx 我需要每次替換都能得到一個不同的ID
    示例:
    <?php
    $str='this is a test for this string includes many this';
    $replace='/this/x';
    $result=preg_replace_callback(
      $replace,
      function($ms){
       static $i;
       $i=$i+1;
       return "that($i)";
      },
      $str
     );
    echo $result,"/n";
    希望本文所述對大家PHP程序設計有所幫助。