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

时间:2015-08-19 17:39:39

标签: php regex php-5.5

我有以下正则表达式:

(<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 = '$1<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

REGEX TESTER

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

1 个答案:

答案 0 :(得分:1)

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

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

Regex101

3v4l