0

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?

0

3 Answers 3

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.