在 PHP 中删除文本字符串的一部分
我已经构建了一个表单,但表单的某些行可能会返回空白,并带有默认值。我正在尝试找到一种搜索表单输出的方法,然后删除我知道不需要的位 - 看起来像:
<tr bgcolor="#FFFFFF">
<td>2E</td>
<td id="8003">-800</td>
</tr>
我已经在几个位上有效地使用了 str_replace() ,但我的主要问题是 bgcolor ="#FFFFFF" 可以更改为不同的十六进制值,也可以
我可以为我猜想的每一个可能的结果编写一个 str_replace() ,但是有没有一个 preg_replace 解决方案可以解决这样的问题?它必须是一个非常复杂的正则表达式。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用正则表达式替换
preg_replace()
< /a>.例如,要删除可变颜色字符串中可能存在或不存在的 bgcolor 属性:但是,与往常一样,不建议使用正则表达式来解析或处理 HTML。很多事情都可能出错:
这仅适用于您问题的有限子集。
使用 DOM 处理方法要健壮得多,PHP 中有多种这种方法的变体。请参阅使用 PHP 和 DOM 解析 HTML。
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:But, as always, it's not recommended to use regular expressions to parse or process HTML. Lots of things can go wrong with this:
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.
难道你不能在 php 中生成正确的 html 而无需稍后通过字符串替换来更改它吗?
也许有一些 IF ELSE 语句。
在我看来,这是一个更好的方法。
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.
匹配十六进制字符串的正则表达式实际上非常简单:
您可能会听说您应该使用 HTML 解析器来删除不需要的节点 - 也许您应该这样做,但是如果您知道输入字符串是什么是这样,那么也许不是。
要匹配示例中的第一行,您需要以下正则表达式:
A regex to match hexadecimal strings is actually quite easy:
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:
在尝试显示该字段之前,您不能在代码中检查该字段是否为“空白”吗?或者放入一些逻辑来不输出,如果它是空白的,则不输出它?
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?