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))\}/';
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.
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:
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.
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.
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))\}/';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With