HTML 标签转换的正则表达式

RegEx for HTML tag conversion

出于某些原因,我想转换包含

的字符串
<p style=“text-align:center; others-style:value;”>Content</p>

<center>Content</center> 在 PHP.

文本对齐值可以是左对齐、右对齐或居中对齐。当有其他样式时,我想省略它们。

我如何在 PHP 中做到这一点?

编辑:

可能是我原来的问题不够清楚。我的意思是,我想将 text-align:center 的内容转换为 <center>,并将 text-align:right 的内容转换为 <right>。当没有文本对齐样式时,我不需要任何包装 div。谢谢。

您可以使用 preg_replace 这样做:

测试 1:

$test = preg_replace('/(<.*”>)(.*)(<\/.*)/s', '<center></center>', '<p style=“text-align:center; others-style:value;”>Content</p>');

var_dump($test);

输出 1:

会 return:

string(24) "<center>Content</center>"

正则表达式 1:

The RegEx 将您的输入分成三个捕获组,其中第一组和第三组可以分配给 open/close p 标签。

正则表达式 2:

如果你愿意,你可以进一步扩展它,用这个 RegEx 来扩展你可能想要的任何其他 tags/quotations/contents。它会将带有任何引号(“或”或'或')的任何标签分为五组,其中第四组($4)是您的目标内容。这种类型的正则表达式通常很有用对于单次出现的非循环字符串,因为它使用 (.*).

测试 2

$test = preg_replace('/<(.*)(\"|\”|\'|\’)>(.*)(<\/.*)/s', '<center></center>', '<p style=“text-align:center; others-style:value;”>Content</p>');

var_dump($test);

正则表达式 3

如果您可能希望获得样式中的任何特定属性,this RegEx 可能会有所帮助:

<(.*)(text-align:)(.*)(center|left|right|justify|inherit|none)(.*)(\"|\”|\'|\’)>(.*)(<\/.*)

测试 3

$tags = [
    '0' => '<p style=“text-align:center; others-style:value;”>Content</p>',
    '1' => '<div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div>',
    '2' => '<span style=\'text-align:right; others-style:value;\' class=\'any class\'>Any Content That You Wish</span>',
    '3' => '<h1 style=“text-align:justify; others-style:value;” class="any class">Any Content That You Wish</h1>',
    '4' => '<h2 style=“text-align:inherit; others-style:value;” class=“any class">Any Content That You Wish</h2>',
    '5' => '<h3 style=“text-align:none; others-style:value;” class=“any class">Any Content That You Wish</h3>',
    '6' => '<h4 style=“others-style:value;” class=“any class">Any Content That You Wish</h4>',
];

var_dump($tag);

$RegEx = '/<(.*)(text-align:)(.*)(center|left|right|justify|inherit|none)(.*)(\"|\”|\'|\’)>(.*)(<\/.*)/s';
foreach ($tags as $key => $tag) {
    preg_match_all($RegEx, $tag, $matches);
    foreach ($matches as $key1 => $match) {
        if (sizeof($match[0]) > 0) {
            $tags[$key] = preg_replace($RegEx, '<></>', $tag);
            break;
        }

    }

}

var_dump($tags);

输出 3

会return:

array(7) {
  [0]=>
  string(24) "<center>Content</center>"
  [1]=>
  string(38) "<left>Any Content That You Wish</left>"
  [2]=>
  string(40) "<right>Any Content That You Wish</right>"
  [3]=>
  string(44) "<justify>Any Content That You Wish</justify>"
  [4]=>
  string(44) "<inherit>Any Content That You Wish</inherit>"
  [5]=>
  string(38) "<none>Any Content That You Wish</none>"
  [6]=>
  string(86) "<h4 style=“others-style:value;” class=“any class">Any Content That You Wish</h4>"
}