Answer the question
In order to leave comments, you need to log in
How to properly use negation in regular expressions?
Good afternoon!
Can you tell me how to properly set up a regular expression?
There is a line:
$str= '
текст 1
<a class="btn" href="https://site.ru/">Ссылка1</a>
текст 2
<a href="https://match.com/">Ссылка2</a>
текст 3
<a class="btn" href="https://fall.com/">Ссылка3</a>
текст 4';
echo preg_replace( '~<(a)[^>]class[^>]*>~siu', "", $str );
echo preg_replace( '~<(a)[^>](?!class)[^>]*>~siu', "", $str );
echo preg_replace( '~<(a)[^>]*?match[^>]+>[^<]+<\/\1>~siu', "", $str );
Answer the question
In order to leave comments, you need to log in
Managed to crack it myself.
https://regex101.com/r/suCdNB/4/
Based on conditional subpatterns:
php.net/manual/ru/regexp.reference.conditional.php
namely:
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
<a
body =body=>
), otherwise ( if match is present ), we apply an empty pattern (that is, we try to find an empty tag <a>
)". <a>
are theoretically possible (although they are safe from the point of view of embedding links in the text), which means that our regular expression does not give a 100% result. Therefore, any invalid abracadabra can be given as a no-pattern (just so that it is not found).<(a)(?(?!match)[^>]|false)+>[^<]*</\1>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question