0

I need to replace img tag. Orginal tag is for example :

<img src="index.php?act=img&amp;sub=article&id=35558" width="150" height="172">

then i want to replace it to :

<img src="index.php?act=img&amp;sub=article&amp;id=35558" style="width: 150px; height: 172"/> 

Id in src is changable.
I dont know how to define proper pattern , i've tried several but none was worked.

Karol85
  • 275
  • 1
  • 4
  • 13

4 Answers4

2

Please, regular expressions are not the right tool for this sort of thing. Regular expressions should be used when you are parsing simple things, HTML is not a regular language anyway.

Please read this article about parsing HTML with PHP

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

This should work:

$img1 = '<img src="index.php?act=img&amp;sub=article&id=35558" width="150" height="172">';
$img2 = preg_replace('/\<img([^>]+)(width|height)="(\d+)"([^>]*)(width|height)="(\d+)"([^>]*)\>/i', '<img$1 style="$2:$3px;$5:$6px"$4$7>', $img1);

The order of parameters(or any additional) does not matter here.

Eugene
  • 3,280
  • 21
  • 17
  • What if the image tag has any other attribute as well? Or it already has a style tag? – Benjamin Gruenbaum Jul 04 '12 at 08:26
  • Benjamin, you answer is definitely right. But not all tasks require such approach. We don't know what's Karol's goal, but his question is plain - he has a number of lines of same pattern and needs to make some replacement. Regular expressions are perfect here. – Eugene Jul 04 '12 at 08:56
  • Thank you. It works very good. My goal was simple , i needed to replace tags in only one format so i thought regex was fit it best. – Karol85 Jul 04 '12 at 11:38
0

I take it you are looking for a regular expression pattern so you can use preg_match to reconstruct the tag? In that case something like this should would:

preg_match('/src="(.+?)".+?width="(.+?)".+?height="(.+?)"/i', $str, $matches);

However, the moment these attributes start changing order, this regular expression won't work anymore. If possible, it would be better to parse the HTML through PHP.

Battle_707
  • 708
  • 5
  • 15
0

This works the way to wanted:P But not recommended to use regex to serve your purpose.

<?php
$string = '<img src="index.php?act=img&amp;sub=article&id=35558" width="150" height="172">';
echo $resultString = preg_replace(array('/\&id\b/i','/width="150" height="172"/i'), array('&amp;id','style="width: 150px; height: 172"'), $string); 
Vimalnath
  • 6,373
  • 2
  • 26
  • 47