Get the number of matching characters in a regex group

I can push the boundaries of regular expressions, but who knows ...

I work on php.

In something like:

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

Is there a way to figure out how many matches '=' (={3,6}) , so that I can highlight it where # # are?

Effectively rotates:

 ===Heading 3=== into <h3>Heading 3</h3> ====Heading 4==== into <h4>Heading 4</h4> ... 
+4
source share
4 answers

You can use:

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

Perfect link

+3
source

No, PCRE cannot do this. Instead, you should use preg_replace_callback and perform the following character count:

  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>"; } 

In addition, you may want to forgive the back signs === . Do not use a backlink, but allow a variable number.

You can also use the /m flag for your regular expression, so you can save ^ instead of the more complex statement (?:\n|^) .

+2
source

It is very simple with the e modifier in regexp, not needed in preg_replace_callback

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

or in this way

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

I would do it like this:

 <?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}>"; } ?> 

Output:

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

Source: https://habr.com/ru/post/1394541/


All Articles