Negative Lookbehind Regex not working in PHPGet the solution ↓↓↓
I wrote a piece of code in PHP that is intended to match an adverb (word ending in 'ly') that should not match any word that is daily, weekly, monthly, bi-daily, bi-weekly, etc.
For example, given the sentence
Locally meet daily for 3 days, only
Locally should match.
I nailed the Regex syntax using negative lookbehind, but PHP is throwing me an error:
Compilation failed: lookbehind assertion is not fixed length at offset..
Here is my full code in PHP:
<?php $sentence = "Locally meet daily for next 3 days"; // Use preg_match() function to check match preg_match('/(\w+ly)(?<!(daily|weekly|monthly))/', $sentence, $matches, PREG_OFFSET_CAPTURE); // Display matches result print_r($matches);
I have tried negative lookahead, but it is not giving me promising results. Would someone please suggest what could be done? Thanks
You can use a negative lookahead, but it needs to be before your match group. You also need to add a word-break (
\b) assertion at the beginning of the regex so that (for example) the regex doesn't match
daily, and another at the end so you don't match words with
ly in the middle e.g.
$sentence = "Locally meet daily newlywed for next 3 days"; preg_match_all('/\b(?!(?:daily|weekly|monthly))(\w+ly)\b/', $sentence, $matches, PREG_OFFSET_CAPTURE); print_r($matches);
Array (  => Array (  => Array (  => Locally  => 0 ) )  => Array (  => Array (  => Locally  => 0 ) ) )
People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.