php - 我的正则表达式没有正确替换

标签 php regex html-parsing preg-replace

我有这个正则表达式:/(?:(?<=(?: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/

相关文章:

javascript - 正则表达式用特殊字符中的所有属性替换 html 标签

python-2.7 - 使用 BS4 解析 HTML 表格

php - 如何在 PHP 中将 CSS 类添加到数组的第一个元素?

PHP Ajax多文件上传超时或内存限制

php - 等于 PHP 参数和 mysql 数据使 foreach 循环不起作用

python - 如何使用 BeautifulSoup 在两个不同的标签之间获取值(value)?

python - Beautifulsoup:如果标签或元素未知,如何查找字符串?

php - 简化我的 Jquery xajax 之类的功能

java - 正则表达式匹配 2 个字符串中的所有匹配项 + Java

regex - 用于版本号解析的正则表达式