我認爲,我們需要您提供的情況多一點信息給你一些有用的東西。做你所描述的最簡單的方法是做類似的事情:
$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