簡體   English   中英

正則表達式:如果在另一個正則表達式中,如何不包括正則表達式

[英]Regex: How to not include a regex if is in another regex

這是我的問題:我有一個包含以下“ html”代碼的php文件:

<div>
    {{ '{# Hi :D #}' }} {# Hello #}
    {{ $model }}
</div>

在我的代碼中,我想讓{##}和{{}}進行不同的正則表達式替換,而不是{{}}中的替換。

這里的問題是,如果我對兩個可能的匹配使用相同的(在PHP中)preg_replace,則不會采用找到的{{}}(這就是我想要的),但是對兩個替換將是相同的:

/{{(.*?)}}|{#(.*?)#}/

這是邏輯,但我想為每個$ 1和$ 2比賽進行不同的替換。

我想到了這些可能性:

  • 首先是告訴正則表達式不要使用“ {{}}”父級中的字符串,但是在多次嘗試之后,我卻沒有這樣做。
  • 第二種可能性是添加另一個替換項,在preg_replace函數中,您可以執行array()替換項,但這不起作用,例如$ 1 =第一個替換項和$ 2 =第二個替換項,每個regex請求都有一個替換項。

在嘗試創建此魔術正則表達式兩天后,我終於在stackoverflow中問了一個問題,希望有人能找到此正則表達式的答案

謝謝,

EDITED

這是將preg_split()PREG_SPLIT_DELIM_CAPTURE標志一起使用的一種方法,用於標記字符串並記入嵌套標簽

$tokens = [
  // token definition as [open_tag, close_tag, replacement]
  ['{{', '}}', '<?php echo \1; ?>'],
  ['{#', '#}', '<?php //\1 ?>']
];

$open_tags = array_column($tokens, 0);
$close_tags = array_column($tokens, 1, 0); // mapped by open tag
$replacements = array_column($tokens, 2, 0); // mapped by open tag

$token_regex = '/(' . implode('|', array_map('preg_quote', $open_tags + $close_tags)) . ')/';

$parts = preg_split($token_regex, $input, -1, PREG_SPLIT_DELIM_CAPTURE);

$output = '';
while (null !== ($part = array_shift($parts))) {

  // open tag found...
  if (in_array($part, $open_tags)) {
    // ...start building string of full tag
    $tag_body = $part;
    // ...watch for corresponding close tag
    $close_at = [ $close_tags[$part] ];
    while (0 < count($close_at)) {
      $inner_part = array_shift($parts);
      if (in_array($inner_part, $open_tags)) {
        // nested tag found, add its closing to watchlist
        array_unshift($close_at, $close_tags[$inner_part]);
      } else {
        // close tag found, remove from watchlist
        if (reset($close_at) === $inner_part) {
          array_shift($close_at);
        }
      }
      $tag_body .= $inner_part;
    }

    // substitute full tag with replacement
    $tag_regex = '/^' . preg_quote($part) . '\s*(.*?)\s*' . preg_quote($close_tags[$part]) . '$/';
    $part = preg_replace($tag_regex, $replacements[$part], $tag_body);
  }

  $output .= $part;
}

echo $output;

您可以在這里嘗試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM