I have a bunch of <P>
tags in an HTML file that I would like to append a unique value to, for example, my HTML file has the following (i've dumped this HTML file into a PHP variable using file_get_contents
):
<P> ... data ... </P>
<P> ... data ... </P>
<P> ... data ... </P>
<P> ... data ... </P>
<P> ... data ... </P>
I would like to change it so it reads this instead:
<P id='unique1'> ... data ... </P>开发者_高级运维
<P id='unique2'> ... data ... </P>
<P id='unique3'> ... data ... </P>
<P id='unique4'> ... data ... </P>
<P id='unique5'> ... data ... </P>
Since this is a regular HTML file, there are other tags that may reside in the file as well (such as <HTML>
, <HEAD>
, <STYLE>
, <BODY>
, etc., but I want to append a unique id to ALL <P>
tags
You need to write a little HTML parser. You can take this as starting point:
<?php
$html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
</head>
<body>
<P> ... data ... </P>
<P> ... data ... </P>
<P> ... data ... </P>
<P> ... data ... </P>
<P> ... data ... </P>
</body>
</html>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$paragraphs = $dom->getElementsByTagName('p');
$count = 0;
foreach($paragraphs as $p){
$count++;
$p->setAttribute('id', 'unique' . $count);
}
echo $dom->saveHTML();
In any case, parsing HTML is not trivial task and handling a list of random IDs in JavaScript is not trivial either. Make sure you have a reason to do all this.
You could simply do this...
$Count = count($MyData);
for ($i = 0; $i < $Count; ++$i) {
echo '<p id="id_' . $MyData[$i]->Id . '">... data ... </p>';
}
Or even this...
$Count = count($MyData);
for ($i = 0; $i < $Count; ++$i) {
echo '<p id="id_' . $i . '">... data ... </p>';
}
Just bear in mind that HTML id attributes must begin with a letter, not a number!
You could use a template engine like Smarty where you can use tags like this to loop over a collection of data:
{foreach from=$myItemsArray item=currentItem}
<p id='unique{$currentItem.id}'>{$currentItem.data}</p>
{/foreach}
This is only reasonable if your page has a certain size and if the data in the HTML file can be generated from a database.
If you really need to process an already existent HTML file, you could use REGEX to replace each <p> tag with <p id='...'>. In PHP the functions are preg_replace or preg_replace_callback. I think if you use preg_replace you need to call it for each occurence of <p> with a limit of 1 so you can increase a counter after every call and then use this counter to replace <p> with <p id='unique$counter'>. This is quite inefficient, that's why i'd recommand using preg_replace_callback where a callback function is executed each time a match is found. I hope it works to increase a counter inside this callback function (I didn't try it).
精彩评论