开发者

How do I search for and replace a specific area of content in a HTML document using preg_replace

开发者 https://www.devze.com 2023-01-08 12:22 出处:网络
I have a HTML document with the a table which I want to replace, however I don\'t know what the content of the table will be so I need to search for the opening and closing table tags and then replace

I have a HTML document with the a table which I want to replace, however I don't know what the content of the table will be so I need to search for the opening and closing table tags and then replace the content between them. I'm a bit of a n00b with regular expressions so I'm having trouble working out how to do this... any ideas?

Update: The HTML in question is available to me as a string and开发者_运维知识库 I'm not able to insert any extra data or change the HTML in any way... I need to be able to search for a opening and closing pattern at the start and end of the table in the HTML and then replace the contents in-between. :)


Do NOT use regular expressons for this, look into parsers. For instance, load the HTML in a DOMDocument instance, search the table with either DOMXPath or getElementsByTagName, and use the replaceNode or other manipulation functions. Doing it with regexes is usually very unreliable.


Is the HTML document your own, or file_get_contents()ed from a another site? If the first, just change the HTML to

<html>
 ...
<table>
    <?php echo $tableString ?>
</table>
 ...
</html>

and give it a .php or .inc extension. Then, in your main file:

<?php
    $tableString = calcTableContents();
    require('includedHTML.inc');
?>

No point parsing HTML if you don't have to.

0

精彩评论

暂无评论...
验证码 换一张
取 消