简体   繁体   English

正则表达式模式匹配以查找和替换

[英]Regex Pattern match to find and replace

I am trying to create a regex pattern to find and then replace my IMG src tags in my HTML template. 我正在尝试创建一个正则表达式模式,以查找然后替换我的HTML模板中的IMG src标记。

Essentially, the pattern should find the contents of the src: 本质上,该模式应该找到src的内容:

And then replace it as such: none 然后将其替换为:none

In above code source is always same data-lazy-src is chnaging 在上面的代码源中,总是在更改data-lazy-src

I'll agree that regex isn't necesarily the right way to do this. 我同意正则表达式不一定是正确的方法。 Here is a solution using the HTML Dom parser: 这是使用HTML Dom解析器的解决方案:

  $html = 'your markup';
  $doc = new DOMDocument();
  $doc->loadHTML($html);

  $tags = $doc->getElementsByTagName('img');
  if(count($tags) > 0) {
       $tag = $tags->item(0);
       $tag->setAttribute('src', $new_src_url);
       $doc->saveHTML($tag);
  }

Then, $doc should have your updated markup with the src atributes of your images changed. 然后, $doc应该使用图像的src属性更改更新的标记。

尝试如下操作:

preg_replace('/(<img.*) src=\"[^"]*\"(.*>)/', '$1 src="none"$2', $html)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM