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
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> 

Link to comment
Share on other sites

::) 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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.