开发者

Deleting portion of a text string in PHP

I've constructed a form, but some rows of the form can potentially be returned blank, with default values. I'm trying to find a way of searching the form output and then deleting the bit which I know is not needed - which looks like:

<tr bgcolor=开发者_开发百科"#FFFFFF">
<td>2E</td>
<td id="8003">-800</td>
</tr>

I've used str_replace() effectively on a couple of bits, but my major problem is that bgcolor="#FFFFFF" can CHANGE to different hex values and also

I could write a str_replace() for every possible outcome I guess, but is there a preg_replace solution for anything like this? It would have to be a pretty complicated regular expression.


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.


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.


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)


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?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜