preg_replace php语法代码

时间:2015-03-12 08:03:02

标签: php syntax preg-replace

我需要将","替换为|,|内部模式而不替换任何其他地方

我喜欢这段代码

[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]

结果必须像这样

[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]

我的代码是:

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

1 个答案:

答案 0 :(得分:2)

此模式旨在仅在第一级或方括号内替换","

$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