A
A
agreIT2020-05-29 16:25:24
PHP
agreIT, 2020-05-29 16:25:24

How to compose a regular expression to select a string outside of the specified tags?

Source line:

Lorem <a href="/article/2020">ipsum dolor</a> sit amet, consectetur adipiscing elit. 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

You need to select all occurrences of " ipsum dolor " that are outside the a
tag. After replacing with links, you should get:
Lorem <a href="/article/2020">ipsum dolor</a> sit amet, consectetur adipiscing elit. 
Lorem <a href="/article/9000">ipsum dolor</a> sit amet, consectetur adipiscing elit. 
Lorem <a href="/article/9000">ipsum dolor</a> sit amet, consectetur adipiscing elit.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2020-05-29
@agreIT

https://regex101.com/r/oT14be/1

$text = preg_replace(
    '#<a\b.*?</a>(*SKIP)(*F)|ipsum dolor#s', 
    '<a href="/article/2020">$0</a>',
    $text
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question