Forum Moderators: phranque

Message Too Old, No Replies

How to Create a File or Directory w/o spaces

         

happystinky

10:37 pm on Dec 16, 2005 (gmt 0)

10+ Year Member



Hi,

I'm really new to this. I have the following code that creates directories based off of a list of entries in a MySQL database. Here is the code:

<?

function directory($result) {

$handle=opendir(".");
while ($file = readdir($handle)) {
if ($file == "." ¦¦ $file == "..") { } else { print "<a href=$file>$file</a><br>"; }

}
closedir($handle);

return $result;
}
echo directory($result);
?>

This generates a menu of directories. I end up with a list of directories like:

my first term
my second term
my third term
ETC.

I need them to end up being more like:

my-first-term
my-second-term
my-third-term
ETC

The reason is that these will be directories on the web and spaces throw everything off.

I know I could just search & replace to replace the spaces with hyphens before I stock the database, but then I'd still have to remove the hyphen for other things I'll need to do later. So, for now it seems like the best thing is just to somehow include a hyphen in the resulting directories so I won't have to deal with that later.

Could anyone lead me in the right direction?

Thanks in advance!

happystinky

10:42 pm on Dec 16, 2005 (gmt 0)

10+ Year Member



By the way, I also have this htaccess that jdmorgan helped me with in the past. What it does is replaces spaces in a url with hyphens but that doesn't solve it either because the files won't physically exist with the hyphens so though the server would look for the correct file, it will not be found.

RewriteCond %{REQUEST_URI} ^(.*)\ (.*)$
RewriteRule ^.*$ %1-%2 [E=space_replacer:%1-%2]
RewriteCond %{ENV:space_replacer}!^$
RewriteCond %{ENV:space_replacer}!^.*\ .*$
RewriteRule ^.*$ %{ENV:space_replacer} [R=301,L]

Don't know if that would be useful or not...

Thanks again!

jdMorgan

2:43 pm on Dec 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



PHP's preg_replace is the usual function used to replace characters:
while ($file = readdir($handle)) { 
if ($file !== "." && $file !== "..") {
$file = preg_replace('/ /','-',$file);
print "<a href=$file>$file</a><br>";
}
}
There may be syntax errors due to the fact that I'm not a PHP coder, but you can fix those. :)

Jim

happystinky

9:10 pm on Dec 17, 2005 (gmt 0)

10+ Year Member



Thanks Jim, that makes a lot of sense. I'll let you know how it turns out. I really appreciate it.