【发布时间】:2022-01-18 11:35:12
【问题描述】:
字符串多次出现 alt attr 键值。在 alt attr 的值中是包含双引号 (") 的字符串。这个双引号使值在第一次出现双引号时终止,而不是取完整值。请帮助修改正则表达式以实现完整的 alt 值
$text = 'advcd<img loading="lazy" class="abcd pqr" alt="chi-phi-sinh-o-benh-v"ien-dai-hoc-y-duoc-co-so-2" attr="val"><img loading="lazy" class="abcd pqr" alt="abcd-sinh-o-benh-"ien-dai-hoc-y-duoc-co-so-3">sdfs';
preg_match_all('/(alt)=(["\'][^"\']*["\'])/i', $text, $matches);
if (count($matches) > 1) {
print_r($matches);
}
电流输出:
Array
(
[0] => Array
(
[0] => alt="chi-phi-sinh-o-benh-v\"
[1] => alt="abcd-sinh-o-benh-\"
)
[1] => Array
(
[0] => alt
[1] => alt
)
[2] => Array
(
[0] => "chi-phi-sinh-o-benh-v\"
[1] => "abcd-sinh-o-benh-\"
)
)
预期输出:
Array
(
[0] => Array
(
[0] => alt="chi-phi-sinh-o-benh-v"ien-dai-hoc-y-duoc-co-so-2"
[1] => alt="abcd-sinh-o-benh-"ien-dai-hoc-y-duoc-co-so-3"
)
[1] => Array
(
[0] => alt
[1] => alt
)
[2] => Array
(
[0] => "chi-phi-sinh-o-benh-v"ien-dai-hoc-y-duoc-co-so-2"
[1] => "abcd-sinh-o-benh-"ien-dai-hoc-y-duoc-co-so-3"
)
)
【问题讨论】:
-
改用 XML 解析器。