仅替换部分正则表达式匹配


Only replace part of regex match

我希望匹配所有具有组合 _[[ 或 ]]_
的字符串

我记下的那部分:(_'['[)|(']']_)
现在是我需要帮助的部分,在这些情况下如何仅替换下划线?

换句话说,字符串:"_[[2, verb//substantiv//adjektiv]]_"将导致字符串:"[[2, verb//substantiv//adjektiv]]"

感谢我能得到的任何帮助。

您可以在此处使用的解决方案是简单地匹配整个模式并将其替换为没有封闭下划线 ( _ 的相同模式。

顺便说一句,我在这里创建了示例。

例:

$str = 'My _[[string to parse]]_ with some _[[examples]]_';
$parsed = preg_replace('/_'['[([^(']']_)]*?)']']_/', "[[$1]]", $str);
echo $parsed;

输出:

我的[[

要解析的字符串]]与一些[[示例]]

正则表达式解释:

  • _'['[要捕获的序列的起点
  • ([^((']']_))]*?)捕获开头和结束序列之间的内容,而不是结束序列本身
  • ']']_结束序列

通过匹配整个模式并使用捕获组捕获内容,可以将模式完全替换为包含匹配模式中内容的新子字符串。

这是在preg_replace的第二个参数中完成的,该参数"[[$1]]"

此处$1代表捕获的组并包含其内容,这些内容将在两组方括号之间插值。

然而,由于模式也匹配下划线(_),它们也会被删除,但只是没有被第二个参数中的任何内容替换。

你可以想出:

$regex = '~
              _'[{2}  # look for an underscore and two open square brackets
              ([^]]+) # capture anything that is not a closing bracket
              ']{2}_  # followed by two closing square brackets and an underscore
          ~x';        # free space mode for this explanation
$string = "_[[2, verb//substantiv//adjektiv]]_";
# in the match replace [[(capture Group 1)]]
$new_string = preg_replace($regex, "[[$1]]", $string);
// new_string = [[2, verb//substantiv//adjektiv]]

观看有关 regex101.com 和 ideone.com 的演示。

如果你愿意

匹配具有组合_[[]]_的所有字符串

您可以使用此正则表达式:

^(?=.*_'['[).+|(?=.*']']_).+$
^               // start of the string
(?=.*_'['[)     // if the string contains _[[
.+              // get the entire string (if the assert is correct)
|               // OR operands (if the assert is not correct, let's check the following)
(?=.*']']_)     // if the string contains ]]_
.+              // get the entire string
$               // end of the string

在这里演示

我只是用这种模式作为一个例子。此处的目标是使用捕获括号。如果模式匹配,您将在匹配数组的索引 n°1 中找到捕获的字符串.

例:

    $pattern = '#_('['[[0-9]+']'])_#';
    $result  = preg_match_all($pattern, '_[[22555]]_ BLA BLA _[[999]]_', $matches);
    if (is_int($result) && $result > 0) {
        var_dump($matches[1]);
    }

输出

array(2) {
  [0]=>
  string(9) "[[22555]]"
  [1]=>
  string(7) "[[999]]"
}

尝试使用您的模式捕获括号[]并将匹配项替换为捕获的内容,如下所示:

$pattern = "/_('['[)|(']'])_/";
$test =  "_[[2, verb//substantiv//adjektiv]]_";
$replace = preg_replace( $pattern ,"$1$2", $test );
echo $replace;

美元符号$允许您使用括号反向引用捕获的内容。 $1表示第一个捕获组,在本例中为 ('['[) ,表示第一对括号,$2引用第二对括号。由于模式使用 | 运算符,因此只有一个捕获组具有匹配项,另一个捕获组将为空。