+6  A: 

You can use regular expression replacement with preg_replace(). For example, to remove a bgcolor attribute that may or may not be there with a variable colour string:

$s = preg_replace('! bgcolor="#[0-9a-fA-F]{6}"!', '', $s);

But, as always, it's not recommended to use regular expressions to parse or process HTML. Lots of things can go wrong with this:

  • 3 letter colour code;
  • single quotes on attribute;
  • no quotes on attribute;
  • variable white space;
  • uppercase attribute;
  • colour names;
  • rgb(N,N,N) and other legal formats;
  • and so on.

And that's just for a limited subset of your problem.

It's far more robust to use DOM processing methods, of which there are several variants in PHP. See Parse HTML With PHP And DOM.

cletus
The DOM processing method is an excellent suggestion. I remember the time when I was preg_matching my way through XML and HTML .. Thank god those days are over.
MiRAGe
Hiya, it's a good idea for sure, but i'm afraid it wouldnt have been half as easy as a good regex in this situation. I knew EXACTLY what the form was outputting, so a regex is safe as houses. The form is dynamically generated - users can add rows, perform operations etc.
hfidgen
A: 

Can you not just check whether the field is "blank" in the code before you get to trying to display it? or put in some logic to not output that if it's blank, don't output it?

Mez
+3  A: 

Couldn't you generate the correct html in php without the need to alter it later with string replacement?

Maybe with some IF ELSE statement.

It seems to me a better approach.

Ismael
+1  A: 

A regex to match hexadecimal strings is actually quite easy:

/[0-9a-fA-F]+/

You'll probably hear that you should use a HTML parser to remove the unwanted nodes - maybe you should, but if you know what the input string is going to be like, then maybe not.

To match that first line in your example, you'd need this regex:

preg_replace("/<tr bgcolor=\"#[0-9a-fA-F]+\">/", '', $string)
nickf
Thanks nick - this was perfect - i've modified it to find the entire string I needed. For various reasons using a parser to get rid of the unwanted fields was less likely to work than this!
hfidgen