Negative Lookbehind Regex not working in PHP
Get 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 sentenceLocally meet daily for 3 days
, onlyLocally
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
Answer
Solution:
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 matchaily
indaily
, and another at the end so you don't match words withly
in the middle e.g.newlywed
:
$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);
Output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Locally
[1] => 0
)
)
[1] => Array
(
[0] => Array
(
[0] => Locally
[1] => 0
)
)
)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function store() on null
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.
Similar questions
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.