Escaping \ for File Paths

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
benauld345
Forum Newbie
Posts: 2
Joined: Fri Jun 13, 2008 11:14 am

Escaping \ for File Paths

Post by benauld345 »

Hi,

I'm writing a function which detects a file path within a string and hyperlink it to that path, i.e: X:\test\test.gif or Z:\test etc etc which will be hyperlinked to file:///Z|test.gif. I've got the regular expression working to detect this:

Code: Select all

([a-zA-Z]):(\\([a-zA-Z0-9_ ]+))+\\?(\.([a-zA-Z0-9_]+))?
which seems to work fine in a regular expression tester, the problem is PHP replaces the \ and leaves blank spaces so it cannot detect any occurances. Is there a way of correcting this? This is the script which I've got so far:

Code: Select all

function autoFile($input)
{
  $data    = explode (" ", $input);
  $output = array();
  foreach ($data as $string) {
    $string = addslashes(htmlspecialchars($string));
    echo $string;
    $output[] = preg_replace("([a-zA-Z]):(\\([a-zA-Z0-9_ ]+))+\\?(\.([a-zA-Z0-9_]+))?","<a href=\"file:///\\1\">\\1</a>", $string);
  }
  return implode (" ", $output);
}
 
echo autoFile("X:\test\test.gif");
Is there a way to fix the escaping \?

Any help will be much appreciated.

Ben
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Escaping \ for File Paths

Post by RobertGonzalez »

You escape the slash with a slash, but need to escape that slash as well. Sounds silly, but usually it would look something like \\ to escape a literal \
benauld345
Forum Newbie
Posts: 2
Joined: Fri Jun 13, 2008 11:14 am

Re: Escaping \ for File Paths

Post by benauld345 »

thanks for the reply, basically it will be taking text from a textbox and writing it to a database but before it does the function needs to generate html to go into the db, is there a way of adding extra \ to the string?
thanks
ben
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: Escaping \ for File Paths

Post by Ollie Saunders »

is there a way of adding extra \ to the string?
Yes there is but I'm confused as to why you need to ask this. You've already demonstrated use of all the things necessary to do this yourself. Just give it a whirl!
Post Reply