gpt4 book ai didi

php - 在 PHP 中使用 REGEX 选择样式属性

转载 作者:可可西里 更新时间:2023-11-01 00:46:03 25 4
gpt4 key购买 nike

我希望在 php 中使用正则表达式获取样式属性及其内容。

例如

输入 <img src="test.png" style="float:left;"/>

期望的输出 style="float:left;"


我尝试过的:

这似乎返回了整个图像,我不确定为什么。我不擅长正则表达式。

$img = '<img src="test.png" style="float:left;"/>';
preg_match('/(<[^>]+) style=".*?"/i', $img, $match);

返回:

    [0] => Array
(
[0] => <img src="test.png" style="float:left;"
[1] => <img src="test.png"
)

谁有任何指点?

干杯。

最佳答案

你几乎是正确的,你只需要捕获你想要的部分,将它括在括号中。您目前正在捕获错误的部分:

$img = '<img src="test.png" style="float:left;"/>';
preg_match('/<[^>]+ (style=".*?")/i', $img, $match);
$result = $match[1];

Demo

注意:这将适用于像示例 <img> 这样的简单输入标记,但是对于任何更复杂的东西,Regex 都不足以解析 HTML,因为 HTML 不是一种常规语言。如果您发现它不够强大,您可以使用 DOMDocument ,这是为这类事情准备的。

关于php - 在 PHP 中使用 REGEX 选择样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18490626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com