0

はい、私のためにこれを行うクラス/パッケージ/システムがすでに存在することは知っていますが、それらを使用できないいくつかの要件と設計上の選択肢があります。独自の単純なマークアップを実装することにしたので、現在行っているよりもヘッダーを処理するためのより良い方法はありますか?

// Basic markup, based on markdown
public static function MarkupToHtml($text) {
    $text = Util::cleanup($text);
    $text = preg_replace('/^[ ]+$/m', '', $text);

    // Add a newline after headers
    // so paragraphs work properly. Should figure out regex so it doesn't
    // add an extra \n if its not needed
    $text = preg_replace('{(^|\n)([=]+)(.*?)(\n)}', "$0\n", $text);

    // Paragraphs
    // Ignore header lines
    $text = preg_replace('{(\n\n|^)([^=])(.|\n)*?(?=\n\n|$)}', '<p>$0</p>', $text);

    // Headers
    // This works, but is there a cleaner way to go about it
    preg_match_all ("/(^|\n)([=]+)(.*?)(\n)/", $text, $matches, PREG_SET_ORDER);
    foreach ($matches as $val) {
        $num = intval(strlen($val[2])) + 2;
        if ($num > 5) {
            $num = 5;
        }
        $text = str_replace($val[0], "<h" . $num . ">" . $val[3] . "</h" . $num .">", $text);
    }

    // Bold
    $text = preg_replace('{([*])(.*?)([*])}', '<strong>$2</strong>', $text);

    // Italic
    $text = preg_replace('{([_])(.*?)([_])}', '<em>$2</em>', $text);

    // mono
    $text = preg_replace('{([`])(.*?)([`])}', "<span style='font-family:monospace;'>$2</span>", $text);


    return $text;
}
4

1 に答える 1

0

preg_match_callback を使用します。

$line = preg_replace_callback(
        '/(^|\n)([=]+)(.*?)(\n)/',
        create_function(
            '$matches',
            '$num = min(intval(strlen($matches[2])) + 2,5);' .
            'return "<h" . $num . ">" . $matches[3] . "</h" . $num .">";'
        ),
        $line
    );
于 2013-04-10T08:51:49.467 に答える