K
K
Kirill Sidorov2011-07-22 07:01:24
PHP
Kirill Sidorov, 2011-07-22 07:01:24

Regexp: negative lookback for tag membership

Faced a problem, it is necessary to wrap some phrases in the document in links. I wrote a regular tag, but here's the problem - I can't handle the exception when the phrase is already wrapped in a link.

<?php
$pattern = '#(?<!")('.$phrase.')(?!</a>)(?!</h1>)(?!</h2>)#iu';
$content = preg_replace($pattern, '<a href="'.$link.'" class="sph">$1</a>', $content);
?>

I added forward checks, but the problem is that if there are more words for the desired phrase, then the checks do not work.For example, a phrase of one word "One",

<a href="/test/">One</a>

in this context is processed normally, link:

<a href="/test/">One ​​two</a> Can you tell me

how to check whether the text belongs to the link?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
B
benipaz, 2011-07-22
@benipaz

not strong in PHP, but in SQL, if a word represents part of a phrase, then it is taken in%. for example %One%.

K
Kindman, 2011-07-22
@Kindman

You can split the content (preg_split) into fragments according to the separator "<a\s.*?", and then process each individual element of the split, and at the end, glue everything together.

S
shadowjack, 2011-07-22
@shadowjack

Hmm, how about something like this:
$pattern = '#(?<!")[^<>]*('.$phrase.')[^<>]*(?!)(?! )(?!)#iu';
?

W
Wott, 2011-07-22
@Wott

retrospective check works from the current position, that is, it is necessary to check not only

</a>
but also
two</a>
guess at once how to do it with a regular expression :) I suggest that it is better to take [ ^ < ] outside the tag *
it will be a little more difficult if you take into account all sorts of spans, strongs and other ems

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question