2013-07-03 42 views
0

我得到了一個大字符串,其中有一些標記,我想改變它以便與fpdf一起使用。取代下一次標記

<span style="text-decoration: underline;">some text</span> 

我需要與

<i>some text</i> 

然而一個簡單的str_replace()函數在這裏更換標籤;不會工作,因爲有跨度標籤,不應該被取代。我需要做一些發現<span style="text-decoration: underline;">

,然後尋找下一個發生</span>,只取代那個。我沒有絲毫知道如何做到這一點。我看過http://us.php.net/strpos,但不知道如何實現,如果這將是解決方案。任何人都可以給我一些指點嗎?

謝謝。

回答

0

這應該做的伎倆:

<?php 
    $in = '<span>Invalid</span><span style="text-decoration: underline;">some text</span><span>Invalid</span>'; 
    $out = preg_replace('@<span style=".*">([^<]+)<\/span>@', '<i>\1</i>', $in); 
    echo $out; 
?> 

View on Codepad.org

您還可以限制你將看到什麼文字的標籤,例如,只有字母數字和空格:

<?php 
    $in = '<span>Invalid</span><span style="text-decoration: underline;">some text</span><span>Invalid</span>'; 
    $out = preg_replace('@<span style=".*">([\w|\s]+)<\/span>@', '<i>\1</i>', $in); 
    echo $out; 
?> 

View on Codepad.org

0
$dom = new domDocument; 
$dom->loadHTML($html); 
$spans = $dom->getElementsByTagName('span'); 
foreach ($spans as $node){ 
    $text = $node->textContent; 
    $node->removeChild($node->firstChild); 
    $fragment = $dom->createDocumentFragment(); 
    $fragment->appendXML('<i>'.$text.'</i>'); 
    $node->appendChild($fragment); 
} 
$out = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace(array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));