2016-06-24 22 views
2

如何刪除文本所有標籤PHP如何去除所有標籤文本在它PHP

我讀其他SO答案,但如預期沒有奏效。我嘗試過/<[^>]*>/和其他reg表達式,但無法使其工作。而strip_tags只會刪除沒有文字的標籤。

這裏是例子,我有:http://www.regexr.com/3dmif

如何刪除在標籤的標籤?像:

<a>test</a> hello mate <p> test2 <a> test3 </a></p> 

輸出應該是:招呼隊友

+0

因此,它不僅是你想要的標籤,而且標籤內的文字? – Epodax

+0

不能使用str_replace()? –

+0

也許https://regex101.com/r/kV8lP2/1?這對於分層元素或自閉元素來說不起作用。 – chris85

回答

3

獲得使用正則表達式將是真的很難,因爲這將需要了解html的範圍,這正則表達式不能因此使用它你的結果將是一個真正的不好的解決方案

一個簡單的解決問題的方法是簡單地解析HTML,並獲得了第一維文本節點。

此代碼片段解決了您提出的問題,但您將不得不根據您的需要進行擴展/更改。

<?php 
// creates a new dom document with your html 
// contents 
$dom = new DOMDocument; 
$dom->loadHTML("<a>test</a> hello mate <p> test2 <a> test3 </a></p>"); 

// always use the body element 
$body = $dom->getElementsByTagName('body')->item(0); 

// prepare your text 
$text = ''; 

// itarete over all items on the first dimension 
// and check if they are a text node: 
foreach($body->childNodes as $node) 
{ 
    if ($node->nodeName === '#text') 
    { 
     $text .= $node->nodeValue; 
    } 
} 

var_dump($text); // hello mate 

乾杯。

編輯:

正如@ splash58指出的那樣,你也可以使用XPath直接訪問文本節點。

<?php 
// creates a new dom document with your html 
// contents 
$dom = new DOMDocument; 
$dom->loadHTML("<a>test</a> hello mate <p> test2 <a> test3 </a></p>"); 
$xpath = new DOMXpath($dom); 

$text = ''; 

foreach ($xpath->query("/html/body/text()") as $node) 
{ 
    $text .= $node->nodeValue; 
} 

var_dump($text); // hello mate 
+2

添加根級別' $ string'並使用xpath'/ html/text()' – splash58

+1

@ splash58真的會更短。 – Mario

+2

是的,這比使用正則表達式更好。最後總會失敗。在你的第一個代碼示例中,最好用'XML_TEXT_NODE'替換'#text''。 –

1

此代碼片段解決了您給定的問題。這對你有幫助。

<?php 

$title = "<a>test</a> hello mate <p> test2 <a> test3 </a></p>"; 

$result = preg_replace("(<([a-z]+)>.*?</\\1>)is","",$title); 
echo $result; // hello mate 

?> 
+1

此西港島線失敗的多,如果你添加更多的圖層:'測試招呼隊友

test2的 TEST3

TEST4

' – Mario

+0

@vishal非常感謝您的幫助。 – whitesiroi

相關問題