Re: preg_match_all problem

From: Date: Tue, 02 Nov 2004 00:34:25 +0000
Subject: Re: preg_match_all problem
Groups: php.general 
Request: Send a blank email to php-general+get-200895@lists.php.net to get a copy of this message
> From: "Ryan A" <ryan@coinpass.com> > Below is my code for a templating kind of script, it basically searches for > 'tags' like this {movies 30} and replaces them, the problem is that if there > are 2 tags (eg: {movies 30}{movies 60}) it only replaces the first one...so > I tried using a preg_match_all... > > I tried using a preg_match_all at: > preg_match($pattern,$content,$matches[]); > but then $res is blank when $res usually contains the tag names... (using a > print_r($res); I just get Array ( [0] => Array ) ) > > ******Start of code********* > > $categories=array("movies","action","cartoons","textlinks"); > > // This gets the tags and put it into matches[] > foreach ($categories as $value) > { > $pattern = "/{".$value." ([0-9_]+)?}/"; > preg_match($pattern,$content,$matches[]); > } > > foreach ($matches as $key =>$value){ > preg_match("/\w+/",$value[0],$res); > //print_r($res); > *******End of code********* > > What am I doing wrong? I see where things are being matched, but how are they being replaced? What you really need here is preg_replace_callback(), probably. <?php $result = preg_replace_callback('/\{([a-z]+) ([0-9]+)\}/i','callback',$yourtext); function callback($matches) { //$matches[1] is movies, cartoons, textlinks, etc //$matches[2] is the number that was matched //this function should return the string to replace //{movies 20} {cartoon 10}, etc... } ?> ---John Holmes... UCCASS - PHP Survey System http://www.bigredspark.com/survey.html

« previous php.general (#200895) next »