Jump to content

help with (.+) the greedy b-tard.


micah1701

Recommended Posts

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

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> 

::) 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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.