more efficient code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

more efficient code

Post 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>';
	}
}
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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";
  }
}
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Post by psurrena »

I don't quite understand the $sp variable. What is assigned to it?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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].
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Post by psurrena »

That's really cool. Thanks for all of your help.
Post Reply