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

Edited by requinix
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.