Page 1 of 1

need help with regex to match string with variable

Posted: Wed Jul 25, 2007 12:50 am
by s.dot
So, continuing on with my development of a templating engine.. man this stuff has begin giving me a headache for like 8 hours solid now.

I need to match a foreach string that looks like this

Code: Select all

{foreach="$errors" value="$error"}
     html here
{/foreach}
My current function (i just want to get a match before I go any farther).

Code: Select all

private function _replace_foreach($src)
{
	foreach($this->_vars_arrays AS $k => $v)
	{
		$k = '$' . "$k";
		echo $k;   //////this prints '$errors'... good  .. if only I could get it in the regex 
		if(preg_match_all("#\{foreach=\"$k\" value=\".+?\"\}.+?{/foreach}#ism", $src, $matches))
		{
			echo '<pre>';
			print_r($matches);
			echo '</pre>';
		} else
		{
			echo 'no matches!';
		}
	}
	
	return $src;
}
I get 'no matches'.
However when I replace $k (which should evalute to the text '$errors') with .+?, the match is found and comes out to {foreach="$errors" value="$error} html {/foreach} appears.. which is weird because $k = '$errors'.

Posted: Wed Jul 25, 2007 3:54 am
by stereofrog
$ is special in regexp, you have to escape it.

Posted: Wed Jul 25, 2007 7:49 am
by s.dot
This is the only way I could get it to work.

Code: Select all

private function _replace_foreach($src)
{
	foreach($this->_vars_arrays AS $k => $v)
	{
		if(preg_match_all("#\{foreach=\"[\$]$k\" value=\".+?\"\}.+?{/foreach}#ism", $src, $matches))
		{
			echo '<pre>';
			print_r($matches);
			echo '</pre>';
		} else
		{
			echo 'no matches!';
		}
	}
	
	return $src;
}
In this case, $k is just the text 'errors' and I have a valid set of characters [\$] to match the dollar sign. Is this odd, or is this just how it works?

(Im glad it works though).

Posted: Wed Jul 25, 2007 8:10 am
by superdezign
Why can't you write in a more readable format?

Code: Select all

if(preg_match_all('#{foreach="\$' . $k . '" value=".+?"}.+?{/foreach}#ism', $src, $matches))

Posted: Wed Jul 25, 2007 8:56 am
by s.dot
superdezign wrote:Why can't you write in a more readable format?

Code: Select all

if(preg_match_all('#{foreach="\$' . $k . '" value=".+?"}.+?{/foreach}#ism', $src, $matches))
For some reason, I was under the assumption that { and } had to be escaped with \, and I'm just used to putting regex's in double quotes.

Yours looks better though, so I changed it.

Posted: Wed Jul 25, 2007 9:01 am
by superdezign
The only time you need to escape the braces is if you want a literal string of {#}, {#,} or {#,#}, where # is a numeric value.