Reputation: 214
I have string like this:
xxx - 12, ABC DEF GHI
I want to replace this string like this
xxx - 12, (ABC DEF GHI)
Moreover the string which I added into bracket is dynamic.
The format is:
STRING - NUMBER, STRING
Brackets starts after NUMBER,
string found and ends at the end of string.
So replace pattern is
STRING - NUMBER, (STRING)
Upvotes: 0
Views: 760
Reputation: 89639
You can try:
$str = preg_replace('~\d,\h*\K.*\S~', '($0)', $str);
pattern details:
~ # 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
~
In the replacement string $0
refers to the whole match, but since I used \K
in the pattern, the whole match is only the part matched by .*\S
.
Feel free to describe what happens before the digit and the comma if needed.
Upvotes: 1