Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regexp negative lookahead

I'm trying match all words wrapped with { } but not the words with "_loop". I can't see where I'm going wrong with my reg expression.

 $content   = '<h1>{prim_practice_name}</h1><p>{prim_content}</p><p>Our Locations Are {location_loop}{name} - {state}<br/>{/location_loop}</p>';
 $pattern = '/\{(\w*(?!\_loop))\}/';
like image 547
user2108258 Avatar asked Mar 25 '13 23:03

user2108258


People also ask

What is negative look ahead in regex?

Negative lookahead. In this type the regex engine searches for a particular element which may be a character or characters or a group after the item matched. If that particular element is present then the regex declares the match as a match otherwise it simply rejects that match.

How to use the regex lookahead syntax in JavaScript?

In this case, you can use the regex lookahead with the following syntax: The lookahead means to search for A but matches only if followed by B. For a number followed by the string lb, you can use the following pattern: The following code uses the regex lookahead syntax to match a number followed by the text lb:

What are lookahead assertions in regex?

Regular Expression Lookahead assertions are very important in constructing a practical regex. They belong to a group called lookarounds which means looking around your match, i.e. the elements before it or the elements after it. Lookaround consists of lookahead and lookbehind assertions.

How does regex search for a particular element?

In this type of lookahead the regex engine searches for a particular element which may be a character or characters or a group after the item matched. If that particular element is not present then the regex declares the match as a match otherwise it simply rejects that match.


1 Answers

This happens because \w* "eats" the stopping word "_loop" before your check, to prevent that you should check the word first (before \w*), like the following:

$pattern = '/\{((?!\w*_loop\})\w*)\}/';

or you can use: ?< ! :

$pattern = '/\{(\w*(?<!_loop))\}/';
like image 111
ole Avatar answered Sep 24 '22 01:09

ole