请问在一段html字符串里如何实现标签替换?

我先有一段html字符串,我想把里面的div,h1类似的标签替换为p标签,例如:

<h1 style="font-size:10px;">这是标题</h1>

替换为:

<p>这是标题</p>

最好是 php 语言的。

阅读 3.6k
4 个回答

正则匹配:

const reg = /<(?:h1|div).*?>\s*(.*?)\s*<\/(?:h1|div)>/gi;

上面的这个正则,目前只匹配h1div标签。

测试:

const html = `<h1 style="font-size:10px;">
  <span>这是标题</span>
</h1>
<div style="font-size:10px;">这是标题</div>`;

const formatTagToP = (html) => {
  const reg = /<(?:h1|div).*?>\s*(.*?)\s*<\/(?:h1|div)>/gi;

  return html.replace(reg, ($1, $2) => {
    if ($1) {
      return `<p>${$2}</p>`;
    }
    return $1;
  });
};

formatTagToP(html); // '<p><span>这是标题</span></p>\n<p>这是标题</p>'

简单封装标签转换


var data = '<h1 style="font-size:10px;">转为p测试</h1><h2 style="font-size:10px;">转为span测试</h2>'


// => <p style="font-size:10px;">转为p测试</p><span style="font-size:10px;">转为span测试</span>
console.log("转换结果", demo(data))

function demo (html) {
  const rules = {
    'h1': 'p',
    'h2': 'span'
  }

  for(const tag in rules) {
    const regStr = `(<)(${tag})(.*?>.*?</)(${tag})(>)`
    const reg = new RegExp(regStr, 'g')
    html = html.replace(reg, function (_, $1, $2, $3, $4, $5) {
      return $1 + rules[tag] + $3 + rules[tag] + $5
    })
  }
  return html
}

使用 Dom 扩展替换即可。这个类似生成JS的DOM对象。而且也支持Xpath搜索。非常强大。

<?php
$s = '<h1 style="font-size:10px;">这是标题</h1><div style="font-size:10px;">我是小蜜蜂</div>';
$s = preg_replace("/<h1.*?>(.*?)<\/h1>/i", '<p>$1</p>', $s);
$s = preg_replace("/<div.*?>(.*?)<\/div>/i", '<p>$1</p>', $s);
echo $s;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题