Reputation: 36311
In a character class can I match full words?
Using this code, the regular expression removes the {else}
tag, so is it possible to add else
inside of the character class as a word, and not as 4 letters?
$section = "
{if {money} == 'yes'}
Sweet!
{else}
Too bad...
{/if}
";
echo preg_replace("/\{[^ \/]+\}/iU", "''", $section);
I thought that this might work (but it doesn't):
echo preg_replace("/\{[^ (else)\/]+\}/iU", "''", $section);
Expected output:
{if '' == 'yes'}
Sweet!
{else}
Too bad...
{/if}
Upvotes: 2
Views: 82
Reputation: 70732
No. You absolutely can not place words inside of a character class []
.
But you can use a Negative Lookahead here instead.
$section = <<<DATA
{if {money} == 'yes'}
Sweet!
{else}
Too bad...
{/if}
DATA;
$section = preg_replace('~\{(?!else|/)\S+\}~i', "''", $section);
echo $section;
See Live demo
Regular expression:
\{ '{'
(?! look ahead to see if there is not:
else 'else'
| OR
/ '/'
) end of look-ahead
\S+ non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times)
\} '}'
Upvotes: 5