1

I need replace "," with |,| inside pattern without replace any other place

i have like this code

[word:"pla pla","pla pla","[other_word:"pla pla","[word:"pla","pla"end word]","pla pla"end other_word]","pla pla","[word:"pla","pla"end word]"end word]

result must be like this

[word:"pla pla|,|pla pla|,|[other_word:"pla pla","[word:"pla","pla"end word]","pla pla"end other_word]|,|pla pla|,|[word:"pla","pla"end word]"end word]

my curent code is :

preg_replace('/\[([\w]+):\"[^\",\"]*\"end\s\w\](.*?)\[([\w]+):\"\"end\s\w\]/', '|^|', $syn);

1 Answer 1

2

This pattern is designed to replace "," only inside the first level or square brackets:

$pattern = '~
# this part defines subpatterns to be used later in the main pattern
(?(DEFINE)
    (?<nestedBrackets> \[ [^][]* (?:\g<nestedBrackets>[^][]*)*+ ] )
)

# the main pattern
(?:            # two possible entry points
    \G(?!\A)   # 1. contiguous to a previous match
  |            #   OR
    [^[]* \[   # 2. all characters until an opening bracket
)

# all possible characters until "," or the closing bracket:
[^]["]* # all that is not ] [ or "
(?:
    \g<nestedBrackets> [^]["]* # possible nested brackets
  |                            #   OR
    "(?!,") [^]["]*            # a quote not followed by ,"
)*+  # repeat as needed
\K   # remove all on the left from match result
(?:
    ","           # match the target
  |
    ] (*SKIP)(*F) # closing bracket: break the contiguity
)
~x';

$str = preg_replace($pattern, '|,|', $str);

demo

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

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.