正则表达式查找自定义符号附带的单词或句子

I need to replace some words or some sentences and convert it to underline. I'm using PHP and find one reference: PHP Regex, extract all custom tags from text

Somehow, the case only covers for single words but not sentences. How to make the regex also can catch everything enclosed by ## tag?

Let say my input will be such as:

"ll the Lorem Ipsum ##generators## on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over ##200 Latin words##, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always ##free from repetition##, injected humour, or non-characteristic words etc."

Then the output will be:

"ll the Lorem Ipsum ____1____ on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over ____2____, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always ____3____, injected humour, or non-characteristic words etc."

Can anyone help me on how to get the regex pattern?

I think the regex is:

/##[^#]+##/g

[Regex Demo]


$text = 'll the Lorem Ipsum ##generators## on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over ##200 Latin words##, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always ##free from repetition##, injected humour, or non-characteristic words etc.';

preg_match_all('/##[^#]+##/', $text, $matches, PREG_SET_ORDER);

for ($i = 0; $i < count($matches); $i++) {
  $text = preg_replace("/".$matches[$i][0]."/", "___".strval($i+1)."___" , $text, 1);
}

[PHP Demo]

Another idea using @shA.t's regex would be the use of preg_replace_callback with a function that increments a variable. So it can be done without loop, which might improve efficiency a bit.

$str = preg_replace_callback('/##[^#]+##/', function($m) use (&$i) {
  return "____". ++$i ."____";
}, $str);

See php demo at eval.in