【问题标题】:How to get style tags using regex or preg_match_all如何使用正则表达式或 preg_match_all 获取样式标签
【发布时间】:2016-10-14 17:50:45
【问题描述】:

我对如何使用 regex 或 preg_match_all 不是很熟悉。 我想获取所有元素的所有样式属性,然后获取字体大小值并将其替换为新值。

示例:

<span style="font-size: 60px;">Coming Soon</span>
<span style="font-size: 60px;">Coming Soon</span>
<span style="font-size: 160px;">Coming Soon</span>
<span style="font-size: 70px;">Coming Soon</span>
<span style="font-size: 260px;">Coming Soon</span>

获取所有元素的所有字体大小,然后将每个大小替换为新值。

$getnewfont = 7*$getfont/16;
$getnewfont = round($getnewfont);
$getnewfont = 'font-size:' . $getnewfont . 'px;line-height:' . $getnewfont . 'px;';
$getnewfont = preg_replace('/"font-size:(.*)\"/i', $getnewfont, $content);

这是我现在所做的,计算还没有完成。 但想法是获取当前元素宽度的等效字体大小。

【问题讨论】:

  • 新值是什么?
  • 你能展示一下你迄今为止尝试过的任何东西吗?
  • 在这里使用正则表达式之前要三思。虽然它看起来很直接,但它非常不灵活。这意味着当 html 结构中的某些细节发生更改时,实现将失败。在大多数情况下,使用 DOM 解析器会更加健壮。看看 PHP 的 simpleDomDomDocument
  • preg_match_all('/style=\"font-size:(.*)\"/i', $content, $output_array);我试过了,但它只有一个 Coming Soon
  • @RomanPerekhrest 我有一个计算会改变字体大小的值,但我需要先获取所有值,然后使用函数获取计算值。

标签: php regex styles preg-replace preg-match-all


【解决方案1】:
s/font-size: [0-9]*px;/font-size: 50px;/g

然后将 50 更改为您想要的值。

【讨论】:

  • 我尝试将它用于我的模式,但它显示错误。警告:preg_match_all():分隔符不能是字母数字或反斜杠 i
【解决方案2】:

在这种情况下无需使用preg_match_all 函数。
preg_replace_callback 函数将完成所有需要的替换:

$html_str = '<span style="font-size: 60px;">Coming Soon</span>
<span style="font-size: 60px;">Coming Soon</span>
<span style="font-size: 160px;">Coming Soon</span>
<span style="font-size: 70px;">Coming Soon</span>
<span style="font-size: 260px;">Coming Soon</span>';

$replaced = preg_replace_callback("/\b(font-size:) (\d{1,3})px;/", function($matches){
    $new_size = round(7 * $matches[2]/16);
    return $matches[1]." ". $new_size. 'px;line-height: '. $new_size. 'px;';
}, $html_str);

print_r($replaced);

输出:

<span style="font-size: 26px;line-height: 26px;">Coming Soon</span>
<span style="font-size: 26px;line-height: 26px;">Coming Soon</span>
<span style="font-size: 70px;line-height: 70px;">Coming Soon</span>
<span style="font-size: 31px;line-height: 31px;">Coming Soon</span>
<span style="font-size: 114px;line-height: 114px;">Coming Soon</span>

http://php.net/manual/en/function.preg-replace-callback.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    相关资源
    最近更新 更多