Helpful Information
 
 
Category: Regex Programming
Inline CSS attributes?

I'm trying to get the width + height from an inline "style" attribute. I've almost got it but I can't get the height without overwriting the width with border-width :argh:

How do I say "Match width or height anywhere (including start of string) except when they are preceded by -" ?


//width pattern
#[^\-]?width:\s*(\d+)px#i

// height pattern
#[^\-]?height:\s*(\d+)px#i

// examples
border-width:0px;height:178px;width:117px;
w: 0
h: 178

width:117px;height:178px;border-width:0px;
w: 117
h: 178

height:178px;width:117px;border-width:0px;
w: 117
h: 178

border-width:0px;
w: 0
h:

You can split up this regexp if you like, I wrote it "all in one":

$strings = array("border-width:0px;height:178px;width:117px;", "width:117px;height:178px;border-width:0px;", "height:178px;width:117px;border-width:0px;", "border-width:0px;");
foreach ( $strings as $string ) {
if (preg_match_all('/(((?<!-)width)|((?<!-)height)):\s*([\d\.]+)/i', $string, $foo) ) {
foreach ( $foo[4] as $key => $val ) {
echo "In the string: <b>{$string}</b> we found {$foo[1][$key]}: {$val}<br />";
}
echo "<P />";
} else {
echo "No matches found for <b>{$string}</b><P />";
}
}
die();The main point is that you need a negative lookbehind:

(?<!-)widthmatches "width without a hyphen in front of it"

-Dan

Thanks Dan - I'll have to try that.

I actually cheated and used explode() :rolleyes: It works but it's more code than seems necessary. Speed is creeping up again... now I'm nearing completion of this script I will soon compare it to DomDocument again.

Here is my klunky explode():


<?php
preg_match('/ width=[\'"]?([0-9]+)[^\'"]?/i', $tag, $wmatches);
preg_match('/ height=[\'"]?([0-9]+)[^\'"]?/i', $tag, $hmatches);

$w = (isset($wmatches[1])) ? $wmatches[1] : '' ;
$h = (isset($hmatches[1])) ? $hmatches[1] : '' ;

if (empty($w) || empty($h))
{
preg_match("# style=['\"](.*)['\"]#i", $tag, $style);

if (isset($style[1]) && ! empty($style[1]))
{
$style_array = explode(';', $style[1]);

//echo '<pre>style: '.print_r($style_array,1).'</pre>';

foreach($style_array as $attr)
{
if (empty($w))
{
preg_match("#^width:\s*(\d+)px#i", $attr, $wmatches);

// if ( ! empty($wmatches)) echo '<pre>wmatches: '.print_r($wmatches,1).'</pre>';

if (isset($wmatches[1]) && ! empty($wmatches[1])) $w = $wmatches[1];
}

if (empty($h))
{
preg_match("#^height:\s*(\d+)px#i", $attr, $hmatches);

// if ( ! empty($hmatches)) echo '<pre>hmatches: '.print_r($hmatches,1).'</pre>';

if (isset($hmatches[1]) && ! empty($hmatches[1])) $h = $hmatches[1];
}

if ( ! empty($w) && ! empty($h)) break;
}
}
}

// errors suppressed because I cannot be bothered to fix filenames like "Alice 6.jpg" just for this =/
if (empty($w) && empty($h)) list($w, $h, $type, $attr) = @ getimagesize($src);
?>










privacy (GDPR)