简体   繁体   English

Markdown. 替换两个匹配 preg_replace

[英]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 **两个例子:** 第一个不起作用:$result_do_not_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); $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结果: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) .请参阅PHP 教程:正则表达式非贪婪(或惰性)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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