I need to replace img tag. Orginal tag is for example :
<img src="index.php?act=img&sub=article&id=35558" width="150" height="172">
then i want to replace it to :
<img src="index.php?act=img&sub=article&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.
This should work:
$img1 = '<img src="index.php?act=img&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.
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
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.
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&sub=article&id=35558" width="150" height="172">';
echo $resultString = preg_replace(array('/\&id\b/i','/width="150" height="172"/i'), array('&id','style="width: 150px; height: 172"'), $string);