preg_replace brain teaser

From: Date: Tue, 15 Apr 2003 14:58:38 +0000
Subject: preg_replace brain teaser
Groups: php.general 
Request: Send a blank email to php-general+get-143953@lists.php.net to get a copy of this message
Hello Everyone I have a slight problem with a regular expression for a preg_replace. I'm trying to match arguments within a string and replace them with a value from an array I pass to a function. Arguments are enclosed in curly braces. To make it clear here is an example: "The dog ate {amount} ducks for dinner and got {feel}." I pass the above string to a function parseArgument $args = array('amount'=>'four', 'feel'=>'sick'); function parseArgument($string, $args) { return preg_replace('/\{([a-zA-Z0-9_-]+?)\}/e', '$args[\\1]', $string); } which should return the result "The dog ate four ducks for dinner and got sick." So far it works. Now I have the problem that opening braces have to be escaped when included in the text. I choose '\' as the escape character. So "The dog \{{amount}} ducks for dinner and got {feel}." passed to the above function should return "The dog {four} ducks for dinner and got sick." In order to do this I changed the pattern from "\{([a-zA-Z0-9_-]+?)\}" to "(?<!\\)\{([a-zA-Z0-9_-]+?)\}" which results in an error: Warning: Compilation failed: lookbehind assertion is not fixed length at offset 31 in d:\eclipse_21\workspace\webframework\classes\I18N.class.php on line 320 First question (this is slightly off topic) I have is why is the lookbehind not a fixed length? It should only be one '\'. Is this a bug in the regex engine or am I missing something? Second question is there a pattern that does the job for me? IMPORTANT: The names in the curly brackets may only contain letters, digits, and '-','_' as stated in the pattern. I have a work around that replaces all occurences of escaped '{' with a differnet pattern such as %%$$%% using str_replace and after doing the preg_replace switching them back. It seems a bit clumsy! SO my goal is to do it all in one regex!!! Thanks for your help in advance Stefan Langer P.S.: Please CC me (slanger at spirit21.de) when replying since I'm on digest.

« previous php.general (#143953) next »