Monday, December 27, 2010

PHP: Store image tag attributes into an array

Code:

<?php
$str = '<img border="0" hspace="2" vspace="2" align="left" width="120" height="120" alt="image" src="path/to/image/image.jpg" />
Some text, another image:<img width="120" height="120" alt="" src="path/to/image/image.jpg" />
and a third<img src="path/to/image/image.jpg" alt="" />';
preg_match_all('~<img ([^>]+)>~i', $str, $matches);

$images = array();
foreach ($matches[1] as $str) {
preg_match_all('~([a-z]([a-z0-9]*)?)=("|\')(.*?)("|\')~is', $str, $pairs);
$images[] = array_combine($pairs[1], $pairs[4]);
}
echo '<pre>' . print_r($images, true) . '</pre>';
?>


Output:
Array
(
[0] => Array
(
[border] => 0
[hspace] => 2
[vspace] => 2
[align] => left
[width] => 120
[height] => 120
[alt] => image
[src] => path/to/image/image.jpg
)

[1] => Array
(
[width] => 120
[height] => 120
[alt] => 
[src] => path/to/image/image.jpg
)

[2] => Array
(
[src] => path/to/image/image.jpg
[alt] => 
)

)

Taken From: http://www.phpfreaks.com/forums/php-coding-help/get-the-array-values-into-img-tags/

No comments:

Post a Comment