2017-08-12 64 views
0

我有串這樣的:PHP的preg_replace加上括號

xxx - 12, ABC DEF GHI 

我要替換此字符串像我加入到支架是動態的,這

xxx - 12, (ABC DEF GHI) 

而且字符串。

的格式是:

STRING - NUMBER, STRING 

支架啓動後NUMBER,字符串中找到,並在字符串的結尾結束。 所以替換模式是

STRING - NUMBER, (STRING) 
+0

它是動態的?決定在何處放置括號的邏輯是什麼?最後11個字符,或者以A開頭的部分,或者最後三個字,或者第一個逗號(trimmed)後面的內容,或者帶有可選內部空格的連續大寫字母,或....? – trincot

+0

我已更新我的問題 – alien

回答

1

讓你的模式和替代是這樣的:

$str = "xxx - 12, ABC DEF GHI"; 
$pattern = "/([A-Z]+ - [0-9]+,) ([A-Z\s]+)/i"; 
$replace = "$1 ($2)"; 
echo preg_replace($pattern,$replace,$str); 

Demo

1

你可以試試:

$str = preg_replace('~\d,\h*\K.*\S~', '($0)', $str); 

圖案的詳細資料:

~   # pattern delimiter 
\d,  # a digit followed by a comma 
\h*  # zero or more horizontal whitespaces 
\K  # start the match result at this position 
.* \S  # zero or more characters until the last non-whitespace character 
~ 

在替換字符串$0指整個比賽,但因爲我在圖案中使用\K,整個匹配是僅由.*\S匹配的部分。

隨意描述在數字和逗號之前會發生什麼,如果需要的話。