2012-04-03 7 views
1

これは、HTMLファイルを次のようになります。最初の<li class="msgln">hello</li>を削除する方法開いているファイルと最初のタグを削除

$fp = fopen("file.html", 'a'); 
.... 
fclose($fp); 

<li class="msgln">hello</li><li class="msgln">hi</li><li class="msgln">hey</li> 

とPHPスクリプト?ファイルの内容が正確である場合

$html = file_get_contents('file.html'); 
$html = preg_replace('#^<li[^>]*>[^<]+</li>#i', '', $html); 

答えて

2

これは最初のliは他のネストされたli Sを含んでいるでしょうしても動作します:regexを使用して

<?php 
$doc = new DOMDocument(); 
$doc->loadHTML('<li class="msgln">hello</li><li class="msgln">hi</li><li class="msgln">hey</li> 
'); 

$root = $doc->documentElement; 
$p = $doc->documentElement->childNodes->item(0)->childNodes; 
$li = $doc->getElementsByTagName('li')->item(0); 
$li->parentNode->removeChild($li); 

$html = ''; 
foreach ($root->childNodes->item(0)->childNodes as $child) { 
    $html .= $doc->saveXML($child); 
} 
echo $html; 

?> 

は、予期しない結果を引き起こす可能性があります。

0

//string contains the file value 
$string = '<li class="msgln">hello</li><li class="msgln">hi</li><li class="msgln">hey</li>'; 

$tag = '</li>'; 

$lis = explode($tag, $string); 

if(count($lis) > 0) { 
    unset($lis[0]); 
    $string = implode($tag, $lis); 
} 
1

あなたはこれを達成するためにpreg_replaceを使用することができます(正規表現なし)、これを試してください記述されているように、次のようなstrip_tags()を使うことができます:

$fp = fopen("file.html", 'a'); 
$content = fread($fp); 
$content = strip_tags($content); 
fclose($fp); 

正規表現を使用することもできますが、これは遅くなります。

1

<li>のコンテンツを動的に変更され

1
$fp = fopen("file.html", 'a'); 
$content = fread($fp); 
$text = preg_replace("/<li.+?>.+?<\/li>/is", "", $content, 1); 
fclose($fp); 
関連する問題