preg_replace_callback 正則替換回調方法用法,


Example #1 preg_replace_callback() 和 匿名函數

<?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|',
        function ($matches) {
            return strtolower($matches[0]);
        },
        $line
    );
    echo $line;
}
fclose($fp);
?>

  

Example #2 preg_replace_callback()示例

<?php
// 將文本中的年份增加一年.
$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);

?>

  

Example #3 preg_replace_callback()使用遞歸構造處理BB碼的封裝

<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";

function parseTagsRecursive($input)
{
     /* 譯注: 對此正則表達式分段分析
     * 首尾兩個#是正則分隔符
     * \[indent] 匹配一個原文的[indent]
     * ((?:[^[]|\[(?!/?indent])|(?R))+)分析:
     *   (?:[^[]|\[(?!/?indent])分析:
     *  首先它是一個非捕獲子組
     *   兩個可選路徑, 一個是非[字符, 另一個是[字符但后面緊跟着不是/indent或indent.
     *   (?R) 正則表達式遞歸
     *     \[/indent] 匹配結束的[/indent]
     * /

    $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';

    if (is_array($input)) {
        $input = '<div style="margin-left: 10px">'.$input[1].'</div>';
    }

    return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}

$output = parseTagsRecursive($input);

echo $output;
?>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM