0

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)
2
  • In which way it is dynamic? What is the logic to decide where to place the brackets? The last 11 characters, or the part that starts with A until the end, or the last three words, or what follows the first comma (trimmed), or consecutive capital letters with optional internal spaces, or ....? Commented Aug 12, 2017 at 11:51
  • I have updated my question Commented Aug 12, 2017 at 11:54

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.