我有这个正则表达式:/(?:(?<=(?:style=["])).*)(line-height.*?)[;"]/i
$regex = '/(?:(?<=(?:style=["])).*)(line-height.*?)[;"]/i';
preg_replace("/(?:(?<=(?:style=[\"'])).*)(line-height.*?)[;\"]/i", "HELLO", $input);
这是输入:
<li><span style="line-height: 20.14399986267089px">500.00dkk</span></li>
<li style="color:red; line-height: 21.14399986267089px"></li>
我只想用 HELLO 替换出现的“line-height: SOMENUMBERpx”(它前面还必须有样式标签): 但我无法让它正常工作。现在它取代了行高属性,但它也取代了:颜色:红色,这是我不想要的。
这是我想要的输出:
<li><span style=HELLO>500.00dkk</span></li>
<li style="color:red; HELLO"></li>
任何人都可以看到我做错了什么吗?
最佳答案
我会使用DOM
解析器提取样式属性并使用 preg_replace()
修改内容:
$input = <<<EOF
<li><span style="line-height: 20.14399986267089px">500.00dkk</span></li>
<li style="color:red; line-height: 21.14399986267089px"></li>
EOF;
# Create a document from input
$doc = new DOMDocument();
$doc->loadHTML($input);
# Create an XPath selector
$selector = new DOMXPath($doc);
# Modify values of the style attributes
foreach($selector->query('//@style') as $style) {
$style->nodeValue = preg_replace(
'/line-height:\s*[0-9]+(\.[0-9]+)?px\s*;?/',
'HELLO;',
$style->nodeValue
);
}
# Output the modified document
echo $doc->saveHTML();
使用DOM
的优势和XPath
即使 HTML 内容变得怪异,您也可以可靠地访问任何嵌套级别中的样式属性。如果将来 HTML 结构发生变化或者您想要更接近地指定哪些样式属性应该更改,那么维护起来也很容易。
以下面的查询为例,它只选择 <span>
的样式属性具有类 even
的标签并且是 div
的子级(在任何嵌套级别)与 id="foo"
.
//div[@id="foo"]//span[contains(@class, "even")]/@style
如果您使用正则表达式尝试此操作,您将会获得很多乐趣! :)
关于CSS
部分。我决定为此使用正则表达式,因为我能想象到的唯一可能破坏正则表达式的东西是这样的:
<span style="background:url('line-height:2px');">
自 line-height:2px
是一个有效的 UNIX 文件名,上面的情况是可能的。但是嘿! :) 如果您真的关心这一点,您将需要使用 CSS 解析器来完成这项工作。
关于php - 我的正则表达式没有正确替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29153239/