返回正则表达式替换......登陆

正则表达式替换html元素属性的方法

巴扎黑2017-01-07 13:04:45937

正则表达式替换任意html元素任意属性,或增加任意属性。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/**

 * 替换html中任意tag内任意attr值

 * @param src_str

 * @param tag

 * @param attr

 * @param val

 * @returns {*}

 */

replace_html_tag_attr: function(src_str, tag, attr, val) {

  if(typeof src_str === 'undefined' || typeof tag === 'undefined' || typeof attr === 'undefined' || typeof val === 'undefined') {

    return '';

  }

  

  var reg = new RegExp('<' + tag + '[^>]*(' + attr + '=[\'\"](\\w*%?)[\'\"])?[^>]*>''gi');

  return src_str.replace(reg, function (match) {

    if(match.indexOf(attr) > 0) {

      //包含attr属性,替换attr

      var sub_reg = new RegExp(attr + '=[\'\"](\\w*%?)[\'\"]''gi');

      return match.replace(sub_reg, attr +'=' + val);

    }else{

      //不包含attr属性,添加attr

      return match.substr(0, tag.length + 1) + ' ' + attr + '=' + val + ' ' + match.substr(tag.length + 2, match.length);

    }

  });

}

更多关于正则表达式替换html元素属性的方法请关注PHP中文网(www.php.cn)其他文章!    


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送