Adrian
Adrian

Reputation: 2291

Accessing subpatterns in regex with preg_replace

I have the following regex:

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

which is matching the following string:

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

And I need to access The cover letter should include so I tried:

    <?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 adds <div class="dotted-highlight"> instead of the desired text: The cover letter should include:

So the output would be:

<ul>

and Expected OUTPUT would be:

The cover letter should include: <ul>

FIDDLE:

http://codepad.org/j8EnRBFI

REGEX TESTER

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

Upvotes: 2

Views: 239

Answers (1)

d0nut
d0nut

Reputation: 2834

Just use this and use the second capture group:

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

Regex101

3v4l

Upvotes: 1

Related Questions