我有一些占位符,用户可以将其插入所见即所得编辑器(其中包含 HTML 代码)中。有时,当它们从 Word 等应用程序粘贴时,它会在其中注入(inject) HTML。
例如:粘贴 %<span>firstname</span>%
而不是%firstname%
.
这是我的正则表达式代码的示例:
$html = '
<p>%firstname%</p>
<p>%<span>firstname</span>%</p>
<p>%<span class="blah">firstname</span>%</p>
<p>%<span><span>firstname</span></span>%</p>
<p>%<span><span><span>firstname</span></span></span>%</p>
<p>%<span class="blah"><span>firstname</span></span>%</p>
<div>other random <strong>HTML</strong> that needs to be preserved.</div>
';
preg_match_all(
'/\%(?![0-9])((?:<[^<]+?>)?[a-zA-z0-9_-]+(?:[\s]?<[^<]+?>)?)\%/U',
$html,
$matches
);
echo '<pre>';
print_r($matches);
echo '</pre>';
输出如下:
Array
(
[0] => Array
(
[0] => %firstname%
[1] => %firstname%
[2] => %firstname%
)
[1] => Array
(
[0] => firstname
[1] => firstname
[2] => firstname
)
)
一旦占位符内有多个跨度,它就不起作用。我不太确定在我的正则表达式中要调整什么。
/\%(?![0-9])((?:<[^<]+?>)?[a-zA-z0-9_-]+(?:[\s]?<[^<]+?>)?)\%/U
我如何实现这一目标?
最佳答案
试试这个正则表达式。它应该可以帮助你!
/\%(?![0-9])(?:<[^<]+?>)*([a-zA-z0-9_-]+)(?:[\s]?<\/[^<]+?>)*\%/U
关于php - 正则表达式匹配其中包含 HTML 的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38389467/