简体   繁体   中英

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.

Essentially, the pattern should find the contents of the src:

And then replace it as such: none

In above code source is always same data-lazy-src is chnaging

I'll agree that regex isn't necesarily the right way to do this. Here is a solution using the HTML Dom parser:

  $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.

尝试如下操作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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