Mazdak
Mazdak

Reputation: 781

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?

Upvotes: 0

Views: 39

Answers (3)

James
James

Reputation: 1123

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;

Upvotes: 2

Bajinder Budhwar
Bajinder Budhwar

Reputation: 83

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

Upvotes: -1

Sarath Kumar
Sarath Kumar

Reputation: 1146

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();
}

Upvotes: 2

Related Questions