RegEx in PHP: match several links in one line of text

Viewed 19

I would like to match url with specific text from long line of text. But the problem is that there can be several links in that line. Sample text:

AAAAAA <a href="https://BBB.com">TEST1</a> CCC <a href="https://DDD.com/EEE-FFF/">GGGG</a> AAAAAA

And I would like to match link with "EEE-FFF" to delete this url later by preg_replace, so my goal is to get:

AAAAAA <a href="https://BBB.com">TEST1</a> CCC GGGG AAAAAA

I tried something like this:

/<a.*?EEE-FFF.*?>(.*?)<\/a>/U

But it match two links as a one. How can I fix it?

1 Answers
<?php
$string = 'AAAAAA <a href="https://BBB.com">TEST1</a> CCC <a href="https://DDD.com/EEE-FFF/">GGGG</a> AAAAAA';
    $pattern = '/<a href="[^"]*EEE-FFF[^"]*">([^<]*)<\/a>/';
    $replacement = '$1';
    echo preg_replace($pattern, $replacement, $string);
?>

Since you want to keep the contents within a matched pattern you want to match it to another group https://regexr.com/6u5d5

Related