Compare string up until character occurance

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
cjackson111
Forum Newbie
Posts: 9
Joined: Sat Jul 04, 2009 6:44 am

Compare string up until character occurance

Post by cjackson111 »

Hello all. I have several documents saved in a directory. Each of these documents have a prefix added to the filename that coresponds to an id# of a record in a database. For instance --

117_myfile.doc
14_expenses.pdf

'117_' would be the format of the prefix added to the filename. More than one file can have the same prefix. What I want to do is display all of the files with a certain prefix. I can already display all of the files in the directory. The code I am using for that is below. I just don't know how to target a certain prefix.

I would appreciate any help thrown my way!

Code: Select all

function DirDisply() { 

$TrackDir=opendir("../doc/bid/"); 

while ($file = readdir($TrackDir)) { 

if ($file == "." || $file == "..") { } 
else {
print "<tr><td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"2\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=../doc/bid/$file target=_blank id=\"black\">$file</a></font></td>";
print "<td></td></tr><br>"; 

} 
} 
closedir($TrackDir); 
return; 
} 

@ DirDisply();
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Compare string up until character occurance

Post by Celauran »

Pass the desired prefix in as an argument and use preg_match()?
cjackson111
Forum Newbie
Posts: 9
Joined: Sat Jul 04, 2009 6:44 am

Re: Compare string up until character occurance

Post by cjackson111 »

Do you have an example? I am not familiar with that.

Thanks!
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Compare string up until character occurance

Post by Celauran »

Sure, try this:

Code: Select all

<?php

function DirDisply($prefix)
{
    // Probably better to pass this in as an argument also
    $TrackDir = opendir("../doc/bid/");

    while ($file = readdir($TrackDir))
    {
        if ($file != "." && $file != ".." && preg_match('/^' . $prefix . '/', $file))
        {
            print "{$file}<br />";
            // print "<tr><td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"2\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"../doc/bid/{$file}\" target=\"_blank\" id=\"black\">{$file}</a></font></td>";
            // print "<td></td></tr><br>";
        }
    }
    closedir($TrackDir);
    return;
}

@ DirDisply('117_');
cjackson111
Forum Newbie
Posts: 9
Joined: Sat Jul 04, 2009 6:44 am

Re: Compare string up until character occurance

Post by cjackson111 »

Ah, that is awesome. Thank you sooooo much!
Post Reply