简体   繁体   中英

Replace occurrence of string in another string with Numbers in PHP

I have a html string code which contain some "img" tags. I want to search the string and change each "<img " occurrence with something like "<img onclick=lightbox(XXXX)" , so the first one should become "<img onclick=lightbox(0)" then the second occurrence should become "<img onclick=lightbox(1)" and then third one should become "<img onclick=lightbox(2)" and etc, How can I achieve this in PHP?

parse the html as a DOMObject and replace

function replace_img($html) {
  $doc = new DOMDocument();
  $doc->loadHTML($html);
  $tags = $doc->getElementsByTagName('img');
  $i=0;
  foreach ($tags as $tag) {       
    $tag->setAttribute('onclick', "lightbox($i)");
    $i++;
  }
   return $doc->saveHTML();
}

A regex-based solution which is a little more elegant and should be a lot faster:

<?php
$string = "<img /><img />";
$i = 0;
$newString = preg_replace_callback( '/<img /', function() use (&$i){
    return '<img onclick="lightbox(' . ($i++) . ');" ';
},$string);
echo $newString;

Here. Try this

<?php 
  $str = "this is xxxx is not equal xxxx, So what xxxx";

  $t = explode('xxxx',$str);
  $i=0;
  $imStr=[];
  foreach($t as $s){
    $s=$s.$i;
    $imStr[$i]=$s;
    $i=$i+1;
  }

  $str = implode($imStr);
  echo $str;
  ?>

This can be improved a lot..

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