在 PHP 中使用正则表达式替换 HTML 属性
好的,我知道我应该使用 DOM 解析器,但这是为了删除一些代码,这些代码是后续功能的概念证明,所以我想在一组有限的测试代码上快速获得一些功能。
我正在尝试去除 HTML 块的宽度和高度属性,换句话说,
width="number" height="number"
用空白字符串替换。
我正在尝试编写的函数目前看起来像这样:
function remove_img_dimensions($string,$iphone) {
$pattern = "width=\"[0-9]*\"";
$string = preg_replace($pattern, "", $string);
$pattern = "height=\"[0-9]*\"";
$string = preg_replace($pattern, "", $string);
return $string;
}
但这不起作用。
我怎样才能做到这一点?
OK,I know that I should use a DOM parser, but this is to stub out some code that's a proof of concept for a later feature, so I want to quickly get some functionality on a limited set of test code.
I'm trying to strip the width and height attributes of chunks HTML, in other words, replace
width="number" height="number"
with a blank string.
The function I'm trying to write looks like this at the moment:
function remove_img_dimensions($string,$iphone) {
$pattern = "width=\"[0-9]*\"";
$string = preg_replace($pattern, "", $string);
$pattern = "height=\"[0-9]*\"";
$string = preg_replace($pattern, "", $string);
return $string;
}
But that doesn't work.
How do I make that work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 在主要语言中是独一无二的,尽管正则表达式以字符串文字的形式指定,如 Python、Java 和 C#,但您还必须使用正则表达式分隔符,如 Perl、JavaScript 和 Ruby。
另请注意,您可以使用单引号代替双引号,以减少转义双引号和反斜杠等字符的需要。 这是一个值得养成的好习惯,因为双引号字符串的转义规则可能会令人惊讶。
最后,您可以通过简单的交替将两个替换项合并为一个:
PHP is unique among the major languages in that, although regexes are specified in the form of string literals like in Python, Java and C#, you also have to use regex delimiters like in Perl, JavaScript and Ruby.
Be aware, too, that you can use single-quotes instead of double-quotes to reduce the need to escape characters like double-quotes and backslashes. It's a good habit to get into, because the escaping rules for double-quoted strings can be surprising.
Finally, you can combine your two replacements into one by means of a simple alternation:
您的模式需要开始/结束模式字符。 像这样:
“/”是常用字符,但大多数字符都可以(“|pattern|”、“#pattern#”等)。
Your pattern needs the start/end pattern character. Like this:
"/" is the usual character, but most characters would work ("|pattern|","#pattern#",whatever).
我认为您缺少需要包围字符串中正则表达式的括号(可以是 //、|| 或各种其他字符对)。 尝试将 $pattern 分配更改为以下形式:
...如果您希望能够进行不区分大小写的比较,请在字符串末尾添加一个“i”,因此:
希望这会有所帮助!
大卫
I think you're missing the parentheses (which can be //, || or various other pairs of characters) that need to surround a regular expression in the string. Try changing your $pattern assignments to this form:
...if you want to be able to do a case-insensitive comparison, add an 'i' at the end of the string, thus:
Hope this helps!
David