preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5)

preg_replace_callback -- 用回呼函數執行正則表達式的搜尋和置換

說明

mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit] )

本函數的行為幾乎和 preg_replace() 一樣,除了不是提供一個 replacement 參數,而是指定一個 callback 函數。該函數將以目的字串中的符合陣列作為輸入參數,並返回用於置換的字串。

例子 1. preg_replace_callback() 例子

<?php
  
// 此文字是用於 2002 年的,
  // 現在想使其能用於 2003 年
  
$text "April fools day is 04/01/2002\n";
  
$text.= "Last christmas was 12/24/2001\n";

  
// 回呼函數
  
function next_year($matches) {
    
// 通常:$matches[0] 是完整的符合項
    // $matches[1] 是第一個括號中的子模式的符合項
    // 以此類推
    
return $matches[1].($matches[2]+1);
  }

  echo 
preg_replace_callback(
              
"|(\d{2}/\d{2}/)(\d{4})|",
              
"next_year",
              
$text);

  
// 結果為:
  // April fools day is 04/01/2003
  // Last christmas was 12/24/2002
?>

You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use create_function() to declare an anonymous function as callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback functions name not used anywhere else.

例子 2. preg_replace_callback()create_function()

<?php
  
/* 一個 UNIX 風格的指令行過濾器,將每個段落開頭的
   * 大寫字母轉換成小寫字母 */

  
$fp fopen("php://stdin""r") or die("can't read stdin");
  while (!
feof($fp)) {
      
$line fgets($fp);
      
$line preg_replace_callback(
          
'|<p>\s*\w|',
          
create_function(
              
// 這裡使用單引號很關鍵,
              // 否則就把所有的 $ 換成 \$
              
'$matches',
              
'return strtolower($matches[0]);'
          
),
          
$line
      
);
      echo 
$line;
  }
  
fclose($fp);
?>

參見 preg_replace()create_function()