Luke Talma
Luke Talma

Reputation: 11

Replacing html link tags with a text description

I've searched around and can't seem to get the right answer. I want to replace all links in a given HTML string like this:

... <a href="link.php">Description Here</a> ...
to:
Description Here: link.php

This is so that non-html email clients can see the link and have the ability to copy and paste them into their browser.

Upvotes: 1

Views: 170

Answers (4)

vdbuilder
vdbuilder

Reputation: 12974

In pure php from a generic html file you could:

<?php
    //an example html string
    $dataStr = '<ul id="sub-menu">
    <li class="parent item10"><a href="link1.php">Arts</a>
        <ul>
            <li class="item29">
                <a href="link2.php">Arts Show</a></li>
            <li class="item29">
                <a href="link3.php">Another Arts Show</a></li>
        </ul>
    </li>
    <li class="parent item15"><a href="link6.php">News</a>
        <ul>
            <li class="item18">
                <a href="link7.php">News Show</a></li>
        </ul>
    </li>
</ul>';


    $startIndex = strpos($dataStr, "<a", 0);
    $endIndex = strpos($dataStr, "</a", $startIndex);

    while (1==1){
        if($startIndex == false || $endIndex == false){
            break;
        }

        $currentLine = substr($dataStr,$startIndex,($endIndex-$startIndex)+4);

        $linkStartIndex = strpos($currentLine, "href=", 0)+6;
        $linkEndIndex = strpos($currentLine, '"', $linkStartIndex);
        $currentLink = substr($currentLine,$linkStartIndex,$linkEndIndex-$linkStartIndex);

        $descriptionStartIndex = strpos($currentLine, ">", $linkEndIndex)+1;
        $descriptionEndIndex = strpos($currentLine, "<", $descriptionStartIndex);
        $currentDescription = substr($currentLine,$descriptionStartIndex,$descriptionEndIndex-$descriptionStartIndex);

        echo ($currentDescription.": ".$currentLink."\n");

        $startIndex = strpos($dataStr, "<a", $endIndex+5);
        $endIndex = strpos($dataStr, "</a", $startIndex);

    }
?>

Upvotes: 1

noob
noob

Reputation: 9202

echo preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/i", "$2: $1", $html);

Upvotes: 1

Paulo H.
Paulo H.

Reputation: 1258

PCRE save you:

$text = '<a href="link.php">Description Here</a>';

echo preg_replace("/\<a.*href=\"(.*)\".*\>(.*)\<\/a\>/Usi",'$2: $1',$text);

Upvotes: 1

rabusmar
rabusmar

Reputation: 4143

You could do something like this:

$text = '<a href="link.php">Description Here</a>';

$replaced = preg_replace('/<a [^>]*href="(.*)"[^>]*>(.*)<\/a>/', '$2: $1', $text);

Upvotes: 1

Related Questions