*
量词是贪婪的,添加 ?
将其变为非贪婪。即你的正则表达式应该是:/<pre(.*?)<\/pre>/s
代码是:
<?php
$input_lines='<pre class="language-php"><code>m1
</code></pre>
lets go
<pre class="language-php"><code>m2
</code></pre>';
$new_string=preg_replace("/(\r?\n?<pre.*?\/pre>\r?\n?)/s","SAMAN",$input_lines);
echo $new_string;
?>
输出:
SAMAN lets go SAMAN
正则表达式模式说明:
( # Begin capture group
\r?\n? # Optional newline characters on Windows and Linux
<pre.*?\/pre> # Match from opening pre tag to closing pre tag
\r?\n? # Optional newline characters on Windows and Linux
) # End capture group
/s # Force all dots in pattern to allow newline characters
我的答案与 LeleDumbo 的答案非常相似,这可能会让提问者感到满意。我只是从结束预标记中省略了不必要的
<
,并包含了一些换行符,以便 $new_string 中没有任何隐藏字符(这可能是也可能不是问题,具体取决于使用情况)。