Jump to content

does not contain between two <> tags?


lfernando

Recommended Posts

Hi there,

 

I've been trying to get this to work but no dice, hope one of you can help me?

I need to find all "<li>" tags that do not contain a certain string, and insert another string.

 

 

For example, find "<li>" tags that do not contain "123" and replace them with "<li id="123">"

// Pear, Watermelon and Tomato do not contain 123
<ul>
<li id="123_1" title="" value="1">Banana</li>
<li id="123_2" title="" value="1">Apple</li>
<li>Pear</li>
<li title="" value="1">Watermelon</li>
<li id="456_2" title="" value="1">Tomato</li>
</ul>

<ul>
<li id="123_1" title="" value="1">Banana</li>
<li id="123_2" title="" value="1">Apple</li>
<li id="123" >Pear</li>
<li id="123"  title="" value="1">Watermelon</li>
<li id="123" title="" value="1">Tomato</li>
</ul>

Any help would be much appreciated!

 

Thank you!

Link to comment
https://forums.phpfreaks.com/topic/287704-does-not-contain-between-two-tags/
Share on other sites

Another way of describing that is adding an id=123 to all LIs that don't already have an id=*123*.

Use DOMDocument.

$html = <<<HTML
<ul>
<li id="123_1" title="" value="1">Banana</li>
<li id="123_2" title="" value="1">Apple</li>
<li>Pear</li>
<li title="" value="1">Watermelon</li>
<li id="456_2" title="" value="1">Tomato</li>
</ul>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

foreach ($dom->getElementsByTagName("li") as $li) {
	if (!$li->hasAttribute("id") || !fnmatch("*123*", $li->getAttribute("id"))) {
		$li->setAttribute("id", "123");
	}
}

$output = "";
foreach ($dom->getElementsByTagName("body")->item(0)->childNodes as $child) {
	$output .= $dom->saveHTML($child);
}

echo $output;
The final $output stuff may vary depending on what your input HTML actually is.

 

...

 

You do realize that it's not allowed to use the same ID for multiple elements, right?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.