![](/img/trans.png)
[英]PHP preg_replace: remove punctuation from beginning and end of string
[英]PHP preg_replace - in case of match remove the beginning and end of the string partly matched by regex with one call?
在PHP中,我嘗試實現以下目標(如果可能,僅使用preg_replace函數):
例子:
$example1 = "\\\\\\\\\\GLS\\\\\\\\\\lorem ipsum dolor: T12////GLS////";
$example2 = "\\\\\\GLS\\\\\\hakunamatata ::: T11////GLS//";
$result = preg_replace("/(\\)*GLS(\\)*(.)*(\/)*GLS(\/)*/", "REPLACEMENT", $example1);
// current $result: REPLACEMENT (that means the regex works, but how to replace this?)
// desired $result
// for $example1: lorem ipsum dolor: T12
// for $example2: hakunamatata ::: T11
當然已經參考了http://php.net/manual/en/function.preg-replace.php ,但是我的替換實驗還沒有成功。
是否可以使用一個preg_replace來實現,還是我必須拆分正則表達式並分別替換前匹配和后匹配?
如果正則表達式根本不匹配,我想收到一個錯誤,但是我可能會先用preg_match進行介紹。
要點是與捕獲組匹配並捕獲您需要的內容,然后替換為對該組的反向引用。 在您的正則表達式中,您對組( (.)*
)應用了一個量詞,因此您無法訪問整個子字符串,只有最后一個字符保存在該組中。
請注意, (.)*
與(.*)
匹配相同的字符串,但是在前一種情況下,捕獲組中將有1個字符,因為正則表達式引擎將捕獲一個字符並將其保存在緩沖區中,然后捕獲另一個字符並重新寫上一個,依此類推。 使用(.*)
表達式,所有字符將被一起抓成一個塊,並作為一個完整的子字符串保存到緩沖區中。
這是一種可能的方法:
$re = "/\\\\*GLS\\\\*([^\\/]+)\\/+GLS\\/+/";
// Or to use fewer escapes, use other delimiters
// $re = "~\\\\*GLS\\\\*([^/]+)/+GLS/+~";
$str = "\\\\\\GLS\\\\\\hakunamatata ::: T11////GLS//";
$result = preg_replace($re, "$1", $str);
echo $result;
IDEONE演示的結果: hakunamatata ::: T11
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.