views:

33

answers:

2

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. :)

+2  A: 

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.

Wrikken
I need to do this server side unfortunately but thanks for the suggestion. :)
Nathan Pitman
Parsing XML server side is what the XML functions of PHP are for.
Kwebble
Wow, ok... I didn't even realise this was possible.. sorry, I just assumed you had misunderstood my question. Will definitely have a look for a primer on native DOM manipulation with PHP. Thanks. :)
Nathan Pitman
@Wrikken: ok, well I found a solution while in part uses the techniques you;ve suggested so thanks very much for that.As I have a large HTML string as a PHP variable it was easier to find the table in question using the DOM method you suggested, replace it with a placeholder node and then str_replace the placeholder node with the string contents. :)Thanks again!
Nathan Pitman
A: 

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.

Eric
That is an interesting interpretation of the question.
Gordon
Often the asker of the question knows what they want, but follow the wrong route to get it.
Eric
Unfortunately I can't effect the HTML in any way before it's available to me as a string in PHP. In retrospect I now realise my original question lacked context so apologies for that. :)
Nathan Pitman