2

私は次のようなものを持っていて<code> <1> <2> </code>、これを取得したいと思います:しかし、これをタグ<code> &lt;1&gt; &lt;2&gt; </code>内にのみ適用し、他の場所には適用したくない。<code></code>

私はすでにこれを持っています:

$txt = $this->input->post('field');
$patterns = array(
    "other stuff to find", "/<code>.*(<).*<\/code>/m"
);
$replacements = array(
    "other stuff to replace", "&lt;"
);

$records = preg_replace($patterns,$replacements, $txt);

<code></code>文字は正常に置き換えられますが、囲まれたタグは削除されます

どんな助けでも大歓迎です!ありがとう

4

2 に答える 2

3

コールバック関数を使用する他の可能性:

<?php
$test = "<code> <1> <2></code> some other text <code> other code <1> <2></code>";
$text = preg_replace_callback("#<code>(.*?)</code>#s",'replaceInCode',$test);
echo htmlspecialchars($test."<br />".$text);

function replaceInCode($row){
    $replace = array('<' => '&lt','>' => '&gt');
    $text=str_replace(array_keys($replace),array_values($replace),$row[1]);
    return "<code>$text</code>";
}

ブロック内に複数の<記号が存在する可能性があるため、2番目の関数なしでこれを実現するのは簡単ではありません(可能かどうかはわかりません)。

詳細はこちら: http: //php.net/preg_replace_callback

于 2012-10-25T14:34:02.913 に答える
0

正規表現を使用してそれを行うことはできますが、一度に行うことはできません。他の交換品は個別に処理することをお勧めします。以下のコードは、<code>セクションの疑似タグを処理します。

$source = '<code> <1> <2> </code>';

if ( preg_match_all( '%<code>(.*?<.*?)</code>%s', $source, $code_sections ) ) {

    $modified_code_sections = preg_replace( '/<([^<]+)>/', "&lt;$1&gt;", $code_sections[1] );
    array_walk( $modified_code_sections, function ( &$content ) { $content = "<code>$content</code>"; } );
    $source_modified = str_replace( $code_sections[0], $modified_code_sections, $source );

}

echo $source_modified;
于 2012-10-25T13:59:50.593 に答える