fork download
  1. <?php
  2.  
  3. $data = <<<DATA
  4. [img]img_patch[/img]
  5. [img=200x150]img_patch[/img]
  6. [img width=200 height=150]img_patch[/img]
  7. [img=width=200xheight=150]img_patch[/img]
  8. [img width=200]img_patch[/img]
  9. DATA;
  10.  
  11. $regex = '~
  12. (?P<tag>\[img[^][]*\])
  13. (?P<src>.+?)
  14. \[/img]
  15. ~x';
  16.  
  17.  
  18. $inner = '~\b(?P<key>width|height)?=(?P<value>[^\s\]]+)~';
  19. $values = '~\d+~';
  20.  
  21. $data = preg_replace_callback($regex,
  22. function($match) use($inner, $values) {
  23. $attr = [];
  24. preg_match_all($inner, $match['tag'], $attributes, PREG_SET_ORDER);
  25. foreach($attributes as $attribute) {
  26. if (!empty($attribute["key"])) $attr[$attribute["key"]] = $attribute["value"];
  27. else {
  28. preg_match_all($values, $attribute["value"], $width_height);
  29. list($attr["width"], $attr["height"]) = array($width_height[0][0], $width_height[0][1]);
  30. }
  31. }
  32.  
  33. // do the actual replacement here
  34. $attr["src"] = $match["src"];
  35. $ret = "<img";
  36. foreach ($attr as $key => $value) $ret .= " $key='$value'";
  37. $ret .= '>';
  38.  
  39. return $ret;
  40. },
  41. $data);
  42.  
  43. echo $data;
  44. ?>
Success #stdin #stdout 0s 82944KB
stdin
Standard input is empty
stdout
<img src='img_patch'>
<img width='200' height='150' src='img_patch'>
<img width='200' height='150' src='img_patch'>
<img width='200' height='150' src='img_patch'>
<img width='200' src='img_patch'>