Page 1 of 1

more efficient code

Posted: Fri Jun 22, 2007 11:07 am
by psurrena
The below code work perfectly. It looks in the appropriate directory, displays all the images with a "t" (thumbnails) and that links to the full size image. The thing is, I feel that the ereg_replace(), which takes away the "t", is a bit of a hack in this situation. Anyone have suggestion on how to clean this up? Thanks in advance.

Code: Select all

/*Check for Images then display the thumbnail */
$path="images/work/".$row['project_id'].'/';
$dir=opendir($path);
while($name=readdir($dir)){
	if (preg_match("/t+([0-9]+)\.jpg$/",$name)){
		$nameb=ereg_replace('t','', $name); //<-- not happy with this
		echo '<a href="'.BASE_URL.$path.$nameb.'" rel="lightbox">';
		echo '<img src="'.BASE_URL.$path.$name.'" alt="'.$row['project_name'].'" width="120" /> ';
		echo '</a>';
	}
}

Posted: Fri Jun 22, 2007 11:17 am
by volka

Code: Select all

/*Check for Images then display the thumbnail */
$path="images/work/".$row['project_id'].'/';
$dir=opendir($path);
while($name=readdir($dir)) {
  if (preg_match("/t+([0-9]+\.jpg)$/",$name, $sp)) {
    echo '<a href="'.BASE_URL.$path.$sp[1].'" rel="lightbox">';
    echo '<img src="'.BASE_URL.$path.$sp[1].'" alt="'.$row['project_name'].'" width="120" /> ';
    echo "</a>\n";
  }
}

Posted: Fri Jun 22, 2007 11:21 am
by psurrena
I don't quite understand the $sp variable. What is assigned to it?

Posted: Fri Jun 22, 2007 12:16 pm
by volka
http://de2.php.net/function.preg-match wrote:int preg_match ( string $pattern, string $subject [, array &$matches [, int $flags [, int $offset]]] )
[...]
matches

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
You have one captured subpattern in the expression
preg_match("/t+([0-9]+\.jpg)$/",$name, $sp))
and therefore the value will be stored in $sp[1].

Posted: Fri Jun 22, 2007 12:25 pm
by psurrena
That's really cool. Thanks for all of your help.