micah1701 Posted March 10, 2008 Share Posted March 10, 2008 I want to parse a string of html and make any link going to a PDF open in a new window. all the links are relative; so they're either: href="/folder/filename.pdf" or href="filename.pdf" This is what I've come up with: <?php $string = 'long string of <a href="/some/folder/file.pdf">html</a> and links'; $pattern = '/href="(\/)?(.+?)\.pdf"/si'; $replace = 'href="$1$2.pdf" target="_blank"'; $string = preg_replace($pattern, $replace, $string); ?> but its just not working. very frustrating. Any thoughts? Thanks!!! Quote Link to comment Share on other sites More sharing options...
effigy Posted March 10, 2008 Share Posted March 10, 2008 It works for me chief, as does this: <pre> <?php $string = 'long string of <a href="/some/folder/file.pdf">html</a> and links'; $pattern = '%(href="/?(?:[^"]+)\.pdf")%si'; $replace = '$1 target="_blank"'; echo $string = preg_replace($pattern, $replace, $string); ?> </pre> Quote Link to comment Share on other sites More sharing options...
micah1701 Posted March 10, 2008 Author Share Posted March 10, 2008 my bad... since you mentioned it worked for you I started looking out of the box and realized there was another problem on my end causing it to not work correctly, completely unrelated to the regex. I do like your code snippet better then mine, so thanks for that!!! I always learn something new when I post a question in this section of the site...even when it turns out I didn't have a real problem after all. Thanks again! Quote Link to comment Share on other sites More sharing options...
effigy Posted March 10, 2008 Share Posted March 10, 2008 Just a quick note about a mistake on my part--the (?:...) wrapper is unnecessary. I'm not sure how that got in there Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.