Greg
Greg

Reputation: 479

Selecting style attribute with REGEX in PHP

I'm looking to get only the style attribute and it's contents using regex in php.

For example

Input <img src="test.png" style="float:left;"/>

Desired Output style="float:left;"


What i've tried:

This seems to return the entire image, and i'm not sure why. I suck at regex.

$img = '<img src="test.png" style="float:left;"/>';
preg_match('/(<[^>]+) style=".*?"/i', $img, $match);

Returns:

    [0] => Array
    (
        [0] => <img src="test.png" style="float:left;"
        [1] => <img src="test.png"
    )

Anyone with any pointers?

Cheers.

Upvotes: 3

Views: 2019

Answers (1)

Paul
Paul

Reputation: 141887

You have it almost correct, you just need to capture the part you want, by surrounding it in parenthesis. You're currently capturing the wrong part:

$img = '<img src="test.png" style="float:left;"/>';
preg_match('/<[^>]+ (style=".*?")/i', $img, $match);
$result = $match[1];

Demo

Note: This will work for simple inputs like the example <img> tag, but for anything more complex Regex is not powerful enough to parse HTML, since HTML is not a regular language. If you find that it's not powerful enough you can use DOMDocument, which is meant for this sort of thing.

Upvotes: 5

Related Questions