preg_replace_callback

(PHP 4 >= 4.0.5)

preg_replace_callback --  正規表現検索を行い、コールバック関数を使用して置換を行う

説明

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

この関数の動作は、ほぼ preg_replace() と同じで すが、replacementの代わりに callbackを指定するところが異なります。この コールバック関数は、subject文字列でマッチした要素の配列が指定され てコールされます。このコールバック関数は、置換後の文字列返す必要 があります。

例 1preg_replace_callback() の例

<?php
  // this text was used in 2002
  // we want to get this up to date for 2003
  $text = "April fools day is 04/01/2002\n";  
  $text.= "Last christmas was 12/24/2001\n";  
  
  // the callback function
  function next_year($matches) {
    // as usual: $matches[0] is the complete match
    // $matches[1] the match for the first subpattern
    // enclosed in '(...)' and so on
    return $matches[1].($matches[2]+1);
  }

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

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

しばしば、1カ所だけで preg_replace_callback()用の callback関数が必要となることがあります。 この場合、preg_replace_callback()をコールする際 に使用するコールバック関数として匿名の関数を宣言するために create_function()を使用することができます。 このようにすることにより、コールに関する全ての情報を1ヶ所に集め、 他の場所で使用されていないコールバック関数名で関数の名前空間を汚染 しないようにすることができます。

例 2 preg_replace_callback()create_function()

<?php
  // a unix-style command line filter to convert uppercase 
  // letters at the beginning of paragraphs to lowercase 

	$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(
                // single quotes are essential here,
                // or alternative escape all $ as \$
                '$matches',
                'return strtolower($matches[0]);'
              ),
              $line
            );
		echo $line;
	}
	fclose($fp);
?>

preg_replace(), create_function()も参照下さい。