仅在<;之间替换特定字符;标签>;及</标签>;在PHP中
我有一些类似于仅在<;之间替换特定字符;标签>;及</标签>;在PHP中,php,regex,replace,tags,Php,Regex,Replace,Tags,我有一些类似于的东西,我想得到这个:12但是我只想在标记中应用它,而不是在其他任何地方 我已经有了这个: $txt = $this->input->post('field'); $patterns = array( "other stuff to find", "/<code>.*(<).*<\/code>/m" ); $replacements = array( "other stuff to replace", "<"
的东西,我想得到这个:12
但是我只想在
标记中应用它,而不是在其他任何地方
我已经有了这个:
$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);
$txt=$this->input->post('field');
$patterns=数组(
“要查找的其他内容”,“/*(您可以使用正则表达式,但不能一次性完成。我建议您单独处理其他替换项。下面的代码将处理部分中的伪标记:
$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;
其他可能性,使用回调函数:
<?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>";
}
如果没有第二个函数,要实现这一点并不容易(甚至不确定是否可能),因为块内可能有多个<符号
请在此处阅读更多信息:
您考虑过使用DOM解析器吗?我需要在php@user990463-PHP包含一个DOM解析器-请参阅使用PHPs类。我需要做一些类似的事情(在我的smileys运行之前替换标记中的all:and=),所以我修改了这段代码,它工作得非常好!为什么你没有站起来投票,这让我感到很惊讶。谢谢你的精彩回答!