Advertisement
Guest User

preg_replace_callback

a guest
Jul 19th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.01 KB | None | 0 0
  1. <?php
  2.  
  3. $content = '<img src="https://img.fotofaze.com/img/ikan.jpg"><br>'.
  4.     '<img src="https://img.fotofaze.com/img/kucing.jpg"><br>'.
  5.     '<img src="https://img.fotofaze.com/img/harimau.jpg"><br>';
  6.  
  7. function img_replace_callback($matches) {
  8.     $url = $matches[1];
  9.     echo $url;
  10.     $domains = array(
  11.         "img01.fotofaze.com",
  12.         "img02.fotofaze.com",
  13.         "img03.fotofaze.com",
  14.         "img04.fotofaze.com",
  15.         "img05.fotofaze.com"
  16.     );
  17.  
  18.     $ori_host = parse_url($url, PHP_URL_HOST);
  19.     $index = crc32($url) % count($domains);
  20.     if ($ori_host == 'img.fotofaze.com') {
  21.         return 'src="'.str_replace('img.fotofaze.com', $domains[$index], $url).'"';
  22.     }
  23.     return 'src="'.$url.'"';
  24. }
  25.  
  26. $counter = 0;    
  27. function replace_img_domain($text) {
  28.     global $counter;
  29.     $text1 = preg_replace_callback(
  30.         '|src="(^"*)"|' ,
  31.         'img_replace_callback',
  32.         $text,
  33.         $counter
  34.     );
  35.     return $text1;
  36. }
  37.  
  38.  
  39. echo '<pre>'.$counter."\n";
  40. var_dump(replace_img_domain($content));
  41. echo '</pre>';
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement