user3197354
user3197354

Reputation: 3

Extracting link from a href and putting it within brackets

I have searched and couldn't find what I was looking for.

This is how it will normally be:

<p>
    Hi how are you? Have you checked <a href="http://www.google.com">Google</a> or <a href="http://www.youtube.com">YouTube</a>?
</p>

But what I would love to have, because I'm willing to apply this on a print or PDF page is the following:

<p>
     Hi how are you? Have you checked <a href="http://www.google.com">Google</a> (<a href="http://www.google.com">http://www.google.com</a>)
     or <a href="http://www.youtube.com">YouTube</a> (<a href="http://www.youtube.com">http://www.youtube.com</a>)?
</p>

Now, I understand that there should be some work with regex, but I don't know how to use that. The text will be taken from the variable $content which has the article in it, and what I would like to have is that all links within $content remain as they are plus the content of href be as an additional hyperlink within brackets "()" so that, hypothetically when someone reads a printed article where hyperlinks are they would be able to see the actual URL.

Upvotes: 0

Views: 255

Answers (2)

Poiz
Poiz

Reputation: 7617

Here is a handy little Function that may suffice.

    <?php

        /**@var string $strInput  THE STRING TO BE FILTERED */
        function doubleUpOnURL($strInput){
            $arrAnchorSplit     = preg_split("#<\/a>#", $strInput);
            $strOutput          = "";
            $anchorRegX         = '(<a\s*href=[\'\"])(.+)([\'\"]>)(.*)';
            foreach($arrAnchorSplit as $anchoredString){
                $strOutput     .= preg_replace("#" . $anchorRegX . "#si" , "$1$2$3$4</a> ($1$2$3$2</a>)", $anchoredString);
            }
            return $strOutput;
        }

        $strInput = '<p>Hi how are you? Have you checked <a href="http://www.google.com">Google</a> or <a href="http://www.youtube.com">YouTube</a>?</p>';

        echo(doubleUpOnURL($strInput));
        //OUTPUTS:
        // Hi how are you? Have you checked Google (http://www.google.com) or YouTube (http://www.youtube.com)?

I hope you find it helpful...

Upvotes: 0

Stuart
Stuart

Reputation: 6780

Use a pseudo element to add the href after your links, something like:

a[href]:after  
{
    content: " (" attr(href) ") ";
}

Upvotes: 2

Related Questions