Home > database >  Markdown. Replacing Two Matches preg_replace
Markdown. Replacing Two Matches preg_replace

Time:12-04

It turns out to make one replacement, but no more than two.

**two examples: ** The first doesn't work: $result_do_not_work The Second one work: $result_work

$text_does_not_work = ' *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content*
[>google!<](LINK:https://google.com)';

$text_work = ' *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content*
[>google!<](LINK:https://google.com)';

$patt = ['~\*spoiler-name\*(.*)\*/spoiler-name\*\*s-content\*\((.*)\)\*/s-content\*~','~\[>(.*)<\]\((.*)\)~'];
$repl=['<details><summary>$1</summary>$2</details>','<a href="$2">$1</a>'];/*<a href="$2">$1</a>*/
$result_work = preg_replace($patt, $repl, $text_work);
$result_does_not_work = preg_replace($patt, $repl, $text_does_not_work);

I tried a many things. For example, this code also does not work: $text='[s]SPOILER[s](content-sp) [s]SPOILER[s](content-sp) [s]SPOILER[s](content-sp)'; $patt = ['/\[s\]([^*] )\[s\]\(([^*] )\)/im']; $repl=['<details><summary>$1</summary>$2</details>']; $page = preg_replace($patt, $repl, $text);

result: SPOILER[s](content-sp) [s]SPOILER[s](content-sp) [s]SPOILER content-sp

CodePudding user response:

The * quantifier is greedy so .* will match as many characters as possible, which is probably not what is required here.

Changing the (.*) to (.*?) may help solve your issue.

See PHP Tutorial: Regex Non-greedy (or Lazy).

  • Related