Replace specific character only between <tag> and </tag> in PHP

*爱你&永不变心* 提交于 2019-12-22 11:37:30

问题


I have something like <code> <1> <2> </code> and I would like to get this : <code> &lt;1&gt; &lt;2&gt; </code> but I want to apply this only inside the <code></code> tags and not anywhere else.

I already have this :

$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);

It replaces successfully the character but it removes the surrounded <code></code> tags

Any help will be very appreciated ! Thanks


回答1:


Other possibility, using callback function:

<?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>";
}

It is not easy (not sure if even possible) to accomplish that without second function, as there can be multiple < symbols inside block.

Read more here: http://php.net/preg_replace_callback




回答2:


You can do it with a regex, but not in one go. I'd suggest you deal with your other replacements separately. The code below will take care of the pseudo tags in your <code> sections:

$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;


来源:https://stackoverflow.com/questions/13068755/replace-specific-character-only-between-tag-and-tag-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!