1

This would be a HTML file:

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

And php script:

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

How to remove first <li class="msgln">hello</li>?

Content in <li> is dynamically changed

enloz
  • 5,704
  • 9
  • 37
  • 56

5 Answers5

2

This will work even if the first li would contain other nested lis:

<?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;

?>

using regex may cause unexpected results.

Community
  • 1
  • 1
stewe
  • 41,820
  • 13
  • 79
  • 75
1

You can use preg_replace to achieve this:

$html = file_get_contents('file.html');
$html = preg_replace('#^<li[^>]*>[^<]+</li>#i', '', $html); 
Sebastian Schmidt
  • 1,078
  • 7
  • 17
1

If the content of the file is exactly as described then you could use strip_tags() such like:

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

Alternatively you could use regular expressions but this would be slower.

Peter
  • 773
  • 1
  • 7
  • 23
1
$fp = fopen("file.html", 'a');
$content = fread($fp);
$text = preg_replace( "/<li.+?>.+?<\/li>/is", "", $content, 1 );
fclose($fp);
0

try this (without regex)

//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);
}
silly
  • 7,789
  • 2
  • 24
  • 37