用文本描述替换html链接标记

时间:2011-12-03 20:01:29

标签: php

我已经四处寻找,似乎无法得到正确的答案。我想替换给定HTML字符串中的所有链接,如下所示:

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

这样非HTML电子邮件客户端就可以看到该链接,并且能够将它们复制并粘贴到浏览器中。

4 个答案:

答案 0 :(得分:1)

你可以这样做:

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

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

答案 1 :(得分:1)

PCRE救你:

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

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

在来自通用html文件的纯PHP中,您可以:

<?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);

    }
?>