Page 1 of 1

Escaping \ for File Paths

Posted: Fri Jun 13, 2008 11:23 am
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

Re: Escaping \ for File Paths

Posted: Fri Jun 13, 2008 11:26 am
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 \

Re: Escaping \ for File Paths

Posted: Fri Jun 13, 2008 11:54 am
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

Re: Escaping \ for File Paths

Posted: Fri Jun 13, 2008 12:04 pm
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!