使用 preg_replace 访问正则表达式中的子模式

Accessing subpatterns in regex with preg_replace

我有以下正则表达式:

(<div class="dotted-highlight">(.*?)\s*){2,}<ul>

匹配以下字符串:

<div class="dotted-highlight">The cover letter should include: <div class="dotted-highlight"><ul>

我需要访问 The cover letter should include 所以我尝试了:

    <?php
    $textarea = '<div class="dotted-highlight">The cover letter should include: 
<div class="dotted-highlight"><ul>';
    $replacing_to = '(<div class="dotted-highlight">(.*?)\s*){2,}<ul>';
    $replacing_with = '<ul>';
    $textarea = preg_replace('#'.$replacing_to.'#', $replacing_with, $textarea);
    ?>

$replacing_with 添加 <div class="dotted-highlight"> 而不是所需的文本:The cover letter should include:

所以输出将是:

<ul>

并且预期输出将是:

The cover letter should include: <ul>

FIDDLE:

http://codepad.org/j8EnRBFI

正则表达式测试器

http://www.regexr.com/3bkb8

只需使用这个并使用第二个捕获组:

((<div class="dotted-highlight">)([^<\n]*)\s?).*?.*?<ul>

Regex101

3v4l