2016-09-29 42 views
2

我有這樣的示例代碼之間移除文本:PHP - 使用用strip_tags來去掉標籤

<?php 

$string='Left text from tag <div title="hello world" class="CSS">What is <b>going on</b> here?<br> Calm up <em>right now</em>.</div> Right text. Possible another <div title="" class="DD">tag..</div> but not always.'; 

echo strip_tags($string); 
?> 

這段代碼的結果是:

Left text from tag What is going on here? Calm up right now. Right text. Possible another tag.. but not always. 

然而,我的目標是消除所有文本(包括標籤)通過此strip_tags函數移除的標籤之間。 IE瀏覽器。結果應該是:

Left text from tag Right text. Possible another but not always. 

我知道它可以用了preg_replace來完成,但是它是太慢了,所以也許有一種更快的解決方案。(沒有必然的關係用strip_tags功能)。

回答

1

在我看來,使用REGEX是最好最緊湊的解決方案。試試這個:

echo preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $string); 

如果你不想使用的preg_replace,使用手冊中的自定義功能strip_tags_content()

function strip_tags_content($text, $tags = '', $invert = FALSE) { 

    preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
    $tags = array_unique($tags[1]); 

    if(is_array($tags) AND count($tags) > 0) { 
     if($invert == FALSE) { 
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } else { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
     } 
    } elseif($invert == FALSE) { 
      return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
    } 
    return $text; 
} 

echo strip_tags_content($string); 

注意:我不認爲使用PHP函數只能實現期望的輸出。您需要以某種方式使用REGEX。

+0

是的,但它可以被不使用的preg_replace完成(即我需要一個更快的解決方案。)。由於strip_tags知道要替換什麼,所以也許它可以用來刪除發現strip_tags之間的文字.. – Tom

+0

我不認爲有任何直接的解決方案,您的問題在構建函數中使用PHP。你必須以某種方式使用REGEX。 –

1

DOMDocument方法如何?

<?php 

$string='Left text from tag <div title="hello world" class="CSS">What is <b>going on</b> here?<br> Calm up <em>right now</em>.</div> Right text. Possible another <div title="" class="DD">tag..</div> but not always.'; 

$dom = new DomDocument(); 
$dom->loadHTML('<body>' . $string . '</body>'); 

$stripped = ''; 
$els = $dom->getElementsByTagName('body')->item(0)->childNodes; 
$len = count($els) - 1; 
foreach($els as $index => $child) { 
    if (is_null($child->tagName)) 
     $stripped .= ' ' . trim($child->nodeValue); 
} 
$stripped = substr($stripped, 1); 

echo $stripped; 

Output

Left text from tag Right text. Possible another but not always. 
+0

它也可以工作(即使現在我不知道什麼是更快,preg_replace或此解決方案:) – Tom

+0

我不知道速度,但你得到的是可讀性。 –

+0

對,即使我沒有打破大腦,我明白它,謝謝.. – Tom