Click to See Complete Forum and Search --> : preg_match Problem


beginnerz
10-10-2005, 03:21 AM
I'm trying to do a function which can read the file name from a path.
For example :
$path = '../myweb/source'

now i need to get the all file name ended with .php which i m trying to use preg_match to get the index.php, but somehow it fail to do so.

wrong example:

$getFileName = preg_match('^../\\[a-z]\\[a-z].php$', $filename[$x], $matches);
print_r($matches);


Any better suggestion. thanks.

LiLcRaZyFuZzY
10-10-2005, 04:08 AM
here is a pattern detection i just wrote, it can both handle slashes and backslashes

<?php
# works with backslashes as well

#$path = '../myweb/source.php';
$path = 'home\df\www.php';
echo $path;

$getFileName = preg_match("/[a-z]+\.[^\.\/]+$/", $path, $matches);
?>
<pre>
<?php
print_r($matches);

?>
</pre>

beginnerz
10-10-2005, 05:05 AM
yea...that's what i need..thankz.
i'm really confused by the pattern detection (^//[a-z]+\\$) the slashes and back slashes. Do u have any references or web site so that i can view with?

LiLcRaZyFuZzY
10-10-2005, 05:19 AM
erm, about references..maybe http://www.php.net/pcre might help ?

bokeh
10-10-2005, 07:45 AM
Although it is possible to do that with a REGEX it is not the right function. The following is much simpler:

$file_n_path = '../path/to/file/file.ext';
$file = basename($file_n_path);
echo $file;

LiLcRaZyFuZzY
10-10-2005, 08:18 AM
yeah, thats what you got from not knowing all the functions! ...

NogDog
10-10-2005, 10:14 AM
One way to accomplish the originally stated requirement:

<?php
$dir = '../myweb/source';
if ($handle = opendir($dir))
{
echo "<h2>PHP files in $dir</h2>\n<ul>\n";
while (false !== ($file = readdir($handle))) {
if(strtolower(array_pop(explode('.', $file))) == "php")
{
echo "<li>$file</li>\n";
}
}
closedir($handle);
echo "</ul>\n";
}
else
{
echo "<p>ERROR: unable to read directory '$dir'.</p>\n";
}
?>