使用preg_replace()替换特殊字符之间的内容
I have a paragraph as -
== one ===
==== two ==
= three ====
etc.
The number of =
sign vary in every row of the paragraph.
I want to write a preg_replace()
expression that will allow me to replace the texts between the =
signs.
example:
== DONE ===
==== DONE ==
= DONE ====
I tried preg_replace("/\=+(.*)\=+/","DONE", $paragraph)
but that doesn't work. Where am I going wrong?
我有一个段落为 - p>
== one = ==
====两个==
=三个====
code> pre>
等。 p>
= code>符号的数量在段落的每一行都有所不同。 p>
我想写一个 preg_replace() 代码> strong>表达式,允许我替换 = code>符号之间的文本 strong>。 p>
示例: p>
== DONE ===
==== DONE ==
= DONE ====
code> pre>
我试过 preg_replace(“/\=+(.*)\=+/”,“DONE”,$ paragraph) code>但这不起作用。 我哪里错了? p>
div>
You can use:
$str = preg_replace('/^=+\h*\K.+?(?=\h*=)/m', 'DONE', $str);
RegEx Breakup:
^ # Line start
=+ # Match 1 or more =
\h* # Match or more horizontal spaces
\K # resets the starting point of the reported match
.+? # match 1 or more of any character (non-greedy)
(?=\h*=) # Lookahead to make sure 0 or more space followed by 1 = is there
You have to place the =
s back.
Also, instead of .*
use [^=]*
(matches characters, which are not =
) so that the =
s don't get eaten up for the replacement.
Additionally, you don't have to escape =
:
preg_replace("/(=+)([^=]*)(=+)/","$1 DONE $3", $paragraph);