在正则表达式组中获取匹配字符数量

4

我可能在挑战正则表达式的极限,但谁知道呢...

我正在使用php进行工作。

就像这样:

preg_replace('/(?:\n|^)(={3,6})([^=]+)(\1)/','<h#>$2</h#>', $input);

有没有办法找出有多少个'=' (={3,6}) 被匹配,这样我就可以在'#'处进行反向引用?

实际上变成:

===Heading 3=== into <h3>Heading 3</h3>
====Heading 4==== into <h4>Heading 4</h4>
...
4个回答

3

您可以使用:

preg_replace('/(?:\n|^)(={3,6})([^=]+)(\1)/e',
             "'<h'.strlen('$1').'>'.'$2'.'</h'.strlen('$1').'>'", $input);

Ideone Link


2
不,PCRE 无法做到这一点。相反,您应该使用 preg_replace_callback 并进行一些字符计数:
  preg_replace_callback('/(?:\n|^)(={3,6})([^=]+)(\1)/', 'cb_headline', $input);

  function cb_headline($m) {
      list(, $markup, $text) = $m;

      $n = strlen($markup);
      return "<h$n>$text</h$n>";
  }

此外,您可能希望在尾随的 === 标记中宽容一些。不要使用反向引用,而是允许可变数量。
您还可以希望对正则表达式使用 /m 标志,这样您就可以将 ^ 保留在更复杂的 (?:\n|^) 断言的位置。

1
+1,顺便说一下,将 (?:\n|^) 替换为 (?m)^(即打开多行模式,使 ^ 成为 行首 锚点而不是 字符串开头)。 - Alan Moore

2
使用正则表达式中的修饰符e非常简单,无需使用preg_replace_callback函数。
$str = '===Heading 3===';
echo preg_replace('/(?:\n|^)(={3,6})([^=]+)(\1)/e',
     'implode("", array("<h", strlen("$1"), ">$2</h", strlen("$1"), ">"));', 
$str);

或者这样

echo preg_replace('/(?:\n|^)(={3,6})([^=]+)(\1)/e',
     '"<h".strlen("$1").">$2</h".strlen("$1").">"', 
$str);

0

我会这样做:

<?php
$input = '===Heading 3===';
$h_tag = preg_replace_callback('#(?:\n|^)(={3,6})([^=]+)(\1)#', 'paragraph_replace', $input);
var_dump($h_tag);

function paragraph_replace($matches) {
    $length = strlen($matches[1]);
    return "<h{$length}>". $matches[2] . "</h{$length}>";
}
?>

输出:

string(18) "<h3>Heading 3</h3>"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接