Redax
Redax

Reputation: 9231

match a string not followed by another (preg_match negative look aheads)

I have to select rows that contain the word one and not another. The rows come form some json string, like those:

{"Name" : "one", "LastError" : "No error", "ID" : 1000 , "Comment" : "no comment"} //YES
{"Name" : "one", "LastError" : "No error", "ID" : 1000 , "Comment" : "another"} //NO because there is 'one' and 'another'

I am using php and preg_match.

I'am trying to use someting like:

if (preg_match('/one.*(?!another)/i',$row_string) > 0)
{
  //no draw
}
else
{
  //Draw something
}

It seems that the look ahead doesn't do anything.

Upvotes: 1

Views: 4009

Answers (2)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

Your regex

/one.*(?!another)/

means match the string one followed by any number of characters, and the string after .* must not match another.

.* will basically match up to the end of the string, so it isn't followed by another.

What you actually want is to match the string one followed by any number of characters, and each of them must not be followed by another.

This one works:

/one(.(?!another))*$/

The $ makes sure that the assertion is tested against every character following one.

To make sure that even one itself isn't preceded by another, we have to add the assertion just after one too:

/one(?!another)(.(?!another))*$/

Upvotes: 8

pamil
pamil

Reputation: 980

one is only in Name? If so, json_decode($json, true).

Upvotes: 0

Related Questions