简体   繁体   中英

Markdown. Replacing Two Matches preg_replace

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); $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

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.

SeePHP Tutorial: Regex Non-greedy (or Lazy) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM