我搜索了四周,似乎無法得到正確的答案。我想,以取代所有的鏈接在給定的HTML字符串是這樣的:用文本描述替換html鏈接標記
... <a href="link.php">Description Here</a> ...
to:
Description Here: link.php
這是爲了讓非HTML電子郵件客戶端可以看到該鏈接,必須複製並粘貼到瀏覽器的能力。
我搜索了四周,似乎無法得到正確的答案。我想,以取代所有的鏈接在給定的HTML字符串是這樣的:用文本描述替換html鏈接標記
... <a href="link.php">Description Here</a> ...
to:
Description Here: link.php
這是爲了讓非HTML電子郵件客戶端可以看到該鏈接,必須複製並粘貼到瀏覽器的能力。
你可以做這樣的事情:
$text = '<a href="link.php">Description Here</a>';
$replaced = preg_replace('/<a [^>]*href="(.*)"[^>]*>(.*)<\/a>/', '$2: $1', $text);
PCRE拯救你:
$text = '<a href="link.php">Description Here</a>';
echo preg_replace("/\<a.*href=\"(.*)\".*\>(.*)\<\/a\>/Usi",'$2: $1',$text);
echo preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/i", "$2: $1", $html);
在純PHP從你可以一個通用的HTML文件:
<?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);
}
?>
也適用於:'Description HereDescription Here'stri ng ...修飾符(U)Ungreedy在這裏很重要,允許多行鏈接,並且(i)允許A標籤。 –