如何刪除文本所有標籤PHP如何去除所有標籤文本在它PHP
我讀其他SO答案,但如預期沒有奏效。我嘗試過/<[^>]*>/
和其他reg表達式,但無法使其工作。而strip_tags
只會刪除沒有文字的標籤。
這裏是例子,我有:http://www.regexr.com/3dmif
如何刪除在標籤的標籤?像:
<a>test</a> hello mate <p> test2 <a> test3 </a></p>
輸出應該是:招呼隊友
如何刪除文本所有標籤PHP如何去除所有標籤文本在它PHP
我讀其他SO答案,但如預期沒有奏效。我嘗試過/<[^>]*>/
和其他reg表達式,但無法使其工作。而strip_tags
只會刪除沒有文字的標籤。
這裏是例子,我有:http://www.regexr.com/3dmif
如何刪除在標籤的標籤?像:
<a>test</a> hello mate <p> test2 <a> test3 </a></p>
輸出應該是:招呼隊友
獲得使用正則表達式將是真的很難,因爲這將需要了解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
此代碼片段解決了您給定的問題。這對你有幫助。
<?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
?>
@vishal非常感謝您的幫助。 – whitesiroi
因此,它不僅是你想要的標籤,而且標籤內的文字? – Epodax
不能使用str_replace()? –
也許https://regex101.com/r/kV8lP2/1?這對於分層元素或自閉元素來說不起作用。 – chris85