Regex to detect filename.pdf in string

I have a string of text and want to be able to detect when a pdf filename exists in the string.

For example:‘… and you can get more info by downloading the pdf file moreinfo.pdf …’

I want to match the ‘moreinfo.pdf’ so I can create a hyperlink to the file. All pdfs are in the same directory so there wont be full paths to the file, just the file name.

I already have this code to match urls:
$text = preg_replace(“/([a-zA-Z]+:\/\/[a-z0-9\_\.\-]+”.
" <a href=\“$1\” target=\“_blank\” title=\“$1\”>link >>></a> ", $text);

But I dont know how to modify it to do what I need. Can someone help me please?

try this -

$text = "...and you can get more info by downloading the pdf file moreinfo.pdf or another file_name.pdf or perhaps one/with/a/directory/path.pdf or one-with-dashes.pdf";
$pattern = "#([a-zA-Z0-9-_\\/]+\\.pdf)#";
$text = preg_replace($pattern,"<a href=\\"$1\\" target=\\"_blank\\" title=\\"$1\\">$1</a>", $text);
echo $text;

or could… ~([\\w/]\\S*?\\.[pP][dD][fF])~
Starts with a-z 0-9 _ / and can contain any amount of non-spaces chars until .pdf

Thanks catweasel that works great.

How is yours different, logic_earth (in behaviour)?

Or more simply,


it allows any character that is not a whitespace character ( space, newlines ) between two boundary parts it must start with either a-z 0-9 _ / and must end with .pdf (case-insensitive)

The boundary is there for a reason while the post simshaun posted is simpler it has a flaw. Example:

blah blah blah file.pdf more blahs go here then call another file (another_file.pdf) some more text.

Now if you use it with out boundaries your link for the last file will be invalid because it will contain the parenthesizes “(”.

Since OP said there won’t be full paths, just the filenames, this should work best