Removing part of a text string in PHP

I created a form, but some of the form lines may be returned empty with default values. I'm trying to find a way to search for the output of a form and then remove a bit that I know isn't needed looks like this:

<tr bgcolor="#FFFFFF">
<td>2E</td>
<td id="8003">-800</td>
</tr>

      

I used str_replace () efficiently for a couple of bits, but my main problem is that bgcolor = "#FFFFF" can CHANGE different hex values ​​as well

I can write str_replace () for every possible result I guess, but is there a preg_replace solution for something like this? It should be a pretty complex regular expression.

+2


source to share


4 answers


The regex matching hex strings is actually pretty simple:

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

      

You will probably hear that you should use an HTML parser to remove unwanted nodes - perhaps you should, but if you know what the input string will look like, perhaps not.



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

preg_replace("/<tr bgcolor=\"#[0-9a-fA-F]+\">/", '', $string)

      

+1


source


You can use regex replacement with preg_replace()

. For example, to remove a bgcolor attribute that may or may not be there with a variable color string:

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

      

But as always, it is not recommended to use regular expressions for parsing or processing HTML. A lot can go wrong:



  • 3-letter color code;
  • single quotes in an attribute;
  • no quotes in the attribute;
  • variable white space;
  • uppercase attribute;
  • color names;
  • rgb (N, N, N) and other legal formats;
  • etc.

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

This is a much more reliable way of using DOM processing methods, of which there are several variations in PHP. See Parsing HTML with PHP and DOM .

+6


source


Couldn't you be able to generate correct html in php without having to change it later with line replacement?

Perhaps with an IF ELSE statement.

The best approach seems to me.

+3


source


Can you not just check if a field is empty in your code before you try to display it? or put in some kind of logic so as not to output, if it's empty don't output it?

0


source







All Articles