2015-06-24 41 views
1

我有許多鏈接的文本。我想這樣每個URL出現其對應的鏈接的名稱和被包裹在括號重新格式化文本 - 和所有標籤被刪除(我寫這CSV)使用PHP重新格式化字符串鏈接

因此,例如,

<a href="http://test.com">TestWebsite1</a> 

變爲...

TestWebsite1 (http://test.com) 

我想的方法是有點乏味:

get index of each occurrence of "<a" 
use regex to get all text following that up to next occurrence of ">" 
find next occurrence of < 
insert text at that index 
str_replace "<a href=「 with "(" 
etc 

我想知道是否有更好的方法...

+2

是的,有,它叫做DOM ..正則表達式+ HTML導致人的犧牲,狗生活在一起貓,歇斯底里。 .. –

+0

http://php.net/manual/en/domdocument.loadhtmlfile.php - 看看例子。 – light

回答

0

請使用正確的HTML解析器:

$html = <<<HTML 
<a href="http://test.com">TestWebsite1</a> 
HTML; 

$doc = new DOMDocument; 
$doc->loadHTML($html); 
$xpath = new DOMXPath($doc); 
foreach ($xpath->query('//a[@href]') as $anchor) { 
    printf("%s (%s)\n", $anchor->textContent, $anchor->getAttribute('href')); 
}