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!!! Link to comment https://forums.phpfreaks.com/topic/95446-help-with-the-greedy-b-tard/ 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> Link to comment https://forums.phpfreaks.com/topic/95446-help-with-the-greedy-b-tard/#findComment-488612 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! Link to comment https://forums.phpfreaks.com/topic/95446-help-with-the-greedy-b-tard/#findComment-488626 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 Link to comment https://forums.phpfreaks.com/topic/95446-help-with-the-greedy-b-tard/#findComment-488631 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.