alien
alien

Reputation: 214

PHP preg_replace add brackets

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

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

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

B. Desai
B. Desai

Reputation: 16436

make your pattern and replacement like this :

$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

Upvotes: 1

Related Questions