我认为,我们需要您提供的情况多一点信息给你一些有用的东西。做你所描述的最简单的方法是做类似的事情:
$output = preg_replace('/.*\("br"\).*/', '<span class="br"></span>', $input);
但我不知道这是你真正想要的。这将删除您的初始字符串中的所有文本,并将其替换为<span class="br"></span>
块,因此您只需重复字符串<span class="br"></span>
即可。
在我听起来像你想要的可能是将块看起来像foo("bar")baz
块像foo<span class="bar"></span>baz
块。如果是这样的话,你可能会想是这样的:
$output = preg_replace('/\("(.*?)"\).*/', '<span class="$1"></span>', $input);
然而,这只是我在我读你的问题的方式最好的猜测。为了真正解决这个问题,我们需要更多地了解,post_string
和br
应该代表什么,以及它们可能如何变化。一些示例输入和输出文本可能会有所帮助,可能会提供一些有关您使用此功能的信息。
编辑:我认为你最近的编辑更清楚一点。它看起来像你试图用正则表达式来解析JavaScript或其他编程语言,由于limitations of regex,你通常不能完美地完成。但是,以下在大多数情况下工作:
$pattern = '/(["\'])\s*\+\s*\w+\((["\'])(.*?)\2\)\s*\+\s*\1/'
$output = preg_replace($pattern, '<span class="$3"></span>', $input);
说明:
/
(["\']) #Either " or '. This is captured in backreference 1 so that it can be matched later.
\s*\+\s* #A literal + symbol surrounded by any amount of whitespace.
\w+ #At least one word character (alphanumeric or _). This is "figure" in your example.
\( #A literal (character.
(["\']) #Either " or '. This is captured in backreference 2.
(.*?) #Any number of characters, but the `?` makes it lazy so it won't match all the way to the last `") + "` in the document.
\2 #Backreference 2. This matches the " or ' from earlier. I didn't use ["\'] again because I didn't want something like 'blah" to match.
\) #A literal) character.
\s*\+\s* #A literal + symbol surrounded by any amount of whitespace.
\1 #Backreference 1, to match the first " or ' quote in the string.
/
希望这是比较容易理解的。可能很难解释什么正则表达式模式正在做,所以我很抱歉,如果这仍然是困难的。如果您仍然感到困惑,请参阅backreferences和lazy quantifiers的更多信息。
我不确定反向引用语法;这些天我通常不用PHP编写代码。如果有人想纠正我,我会很欢迎。
请给出一个真正的示例字符串和预期输出。 – mario 2011-04-21 22:20:17
@mario真实信息添加 – morgar 2011-04-21 22:37:01