问题
I have something like <code> <1> <2> </code>
and I would like to get this : <code> <1> <2> </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", "<"
);
$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('<' => '<','>' => '>');
$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( '/<([^<]+)>/', "<$1>", $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