如何对 PHP 中字符串中的所有匹配项执行正则表达式标记转换?
How to perform regex tag conversions to all occurrences in a string in PHP?
我想将包含 <p style=“text-align:center; others-style:value;”>Content</p>
的 html 字符串转换为 <center>Content</center>
,将 <p style=“text-align:right; others-style:value;”>Content</p>
转换为 <right>Content</right>
等
有一个答案可以完美地实现这一点。正则表达式是:
$RegEx = '/<(.*)(text-align:)(.*)(center|left|right|justify|inherit|none)(.*)(\"|\”|\'|\’)>(.*)(<\/.*)/s';
$string = preg_replace($RegEx, '<></>', $string);
但是,我的字符串可能包含多次文本对齐。例如,我可能有 <div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>
我希望它变成 <left>Any Content That You Wish</left><center>Content</center>
,但它只会输出 <center>Content</center>
.
如何在 PHP 中得到我想要的东西?非常感谢。
正如我在评论中所写,您不应使用正则表达式来操纵 html 内容。但只有当你的 html 中有非嵌套标签时,你才可以使用它。
对于这种特殊情况,您可以使用此正则表达式,
<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</>
并替换为<></>
$html = '<p style=“text-align:center; others-style:value;”>Content</p>
<div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>';
$newhtml = preg_replace("~<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</\1>~", '<></>', $html);
echo $newhtml;
打印,
<center>Content</center>
<left>Any Content That You Wish</left><center>Content</center>
我想将包含 <p style=“text-align:center; others-style:value;”>Content</p>
的 html 字符串转换为 <center>Content</center>
,将 <p style=“text-align:right; others-style:value;”>Content</p>
转换为 <right>Content</right>
等
$RegEx = '/<(.*)(text-align:)(.*)(center|left|right|justify|inherit|none)(.*)(\"|\”|\'|\’)>(.*)(<\/.*)/s';
$string = preg_replace($RegEx, '<></>', $string);
但是,我的字符串可能包含多次文本对齐。例如,我可能有 <div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>
我希望它变成 <left>Any Content That You Wish</left><center>Content</center>
,但它只会输出 <center>Content</center>
.
如何在 PHP 中得到我想要的东西?非常感谢。
正如我在评论中所写,您不应使用正则表达式来操纵 html 内容。但只有当你的 html 中有非嵌套标签时,你才可以使用它。
对于这种特殊情况,您可以使用此正则表达式,
<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</>
并替换为<></>
$html = '<p style=“text-align:center; others-style:value;”>Content</p>
<div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>';
$newhtml = preg_replace("~<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</\1>~", '<></>', $html);
echo $newhtml;
打印,
<center>Content</center>
<left>Any Content That You Wish</left><center>Content</center>