我有一个字符串,例如:
This is text outside \r \n of pre tags
<pre class="myclass"> Text inside \r \n pre tags</pre>
This is text \r \n \r\n outside of pre tags
请问有谁能帮我解决如何替换和删除 \r \n,但是只在 <pre>
标签之外(<pre class="myclass"></pre>
内容不会被替换)?
如何使用 PHP 正则表达式和 preg_replace() 或其他方法实现?
我有一个变量中的文本 $text = 'text<pre class="myclass">text</pre>text';
非常感谢您的帮助。
更新:
感谢大家的回复,对我很有帮助,我会考虑 DOM,我已经尝试过 preg_split(),似乎可以满足我的需求,也许对别人有用 - 替换 <pre class="myclass"></pre>
标签之外的 \r\n:
function ReplaceOutsidePreTags($text) {
$parts = preg_split('/(\<pre class="myclass"\>.+?\<\/pre\>)/s',$text,-1,PREG_SPLIT_DELIM_CAPTURE);
$text_new = '';
foreach ($parts as $key=>$value) {
if (preg_match('[<pre class="myclass">|</pre>]',$value) == true) {
$text_new .= $value;
} else {
$text_new .= str_replace(array("\\r\\n","\\n","\\r"),array("","",""), $value);
}
}
return $text_new;
}
$text = 'this is text\r\n\r\r\n\n outside pre tag\r\n
<pre class="myclass">graphics,\r\n\r\nprogramming </pre>
this is text outside\r\n pre tag\r\n
<pre class="myclass">graphics,\r\n\r\nprogramming </pre>
this is text outside\r\n pre tag\r\n
<pre class="myclass">graphics,\r\n\r\nprogramming </pre>
this is text outside pre tag\r\n';
$text_new = $this->ReplaceOutsidePreTags($text);
echo $text_new;
结果>
this is text outside pre tag
<pre class="myclass">graphics,\r\n\r\nprogramming </pre>
this is text outside pre tag
<pre class="myclass">graphics,\r\n\r\nprogramming </pre>
this is text outside pre tag
<pre class="myclass">graphics,\r\n\r\nprogramming </pre>
this is text outside pre tag