2

<code> 削除するもの </code> 内のコンテンツに対してのみ htmlentities() を実行したい

文字列を受け取り、 <code> </code> の間のコンテンツを見つける関数を作成しました

function parse_code($string) {

        // test the string and find contents with <code></code>
        preg_match('@<code>(.*?)</code>@s', $string, $matches);

            // return the match if it succeeded
            if($matches) {
                return $matches[1];
            }else {
                return false;
            }
    }

ただし、実際に htmlentities(); を実行する関数について助けが必要です。<code> </code> 内のコンテンツを処理し、implode() ですべてを元に戻します。たとえば、以下の文字列があるとします。

<div class="myclass" rel="stuff"> ここにあるもの </div>
<code> ここでは htmlentites() のみを実行するため、 < > " ' & </code> などを削除します
<div> ここにあるもの </div>

繰り返しますが、関数は文字列のすべての内容を同じに保つ必要がありますが、変更して <code> </code> の内容に対してのみ htmlentities() を実行する必要があります。

4

1 に答える 1

5

カスタム コールバック関数を使用してこれを簡素化できます。

$html = preg_replace_callback(
     "@  (?<= <code>)  .*?  (?= </code>)  @six",
     "htmlentities_cb", $html
);

function htmlentities_cb($matches) {
    return htmlentities($matches[0], ENT_QUOTES, "UTF-8");
}

囲んでいるコード タグを照合するための構文は、後読みアサーションおよび先読みアサーションと呼ばれます。アサーションの一致自体が $matches[0] の一部にならないため、コールバックを簡素化し、後で implode() を回避します。@six は大文字と小文字を区別しないタグの一致用であり、正規表現の空白を使用して読みやすくします。

于 2011-02-14T05:20:20.407 に答える