How can I get the value of the class on a string like this:
$string = 'some text <div class="myClassValue">text</div> some text';
Keeping in mind that in the string there could be more than 1 divs with classes.
How can I get the value of the class on a string like this:
$string = 'some text <div class="myClassValue">text</div> some text';
Keeping in mind that in the string there could be more than 1 divs with classes.
As John Conde commented, you shouldn't use Regex for parsing HTML. Things can get really complex because of hierarchy, different tags, invalid code, you name it. Oh yeah, and performance is horrible.
However, in this particular case you might be dealing with an HTML element, but you don't require parsing it. So I think a regular expression wouldn't hurt in this case.
preg_match_all('/class="(.*?)"/i', $string, $matches);
var_dump($matches); // array of matches
$matches[0]
will contain entire matches (class="myClass"
)
$matches[1]
will contains the classes only (myClass
)
try simple html dom parser -> http://simplehtmldom.sourceforge.net/, you can loop through the divs if necessary
Also don't use regex as John Conde noted, use it only in worst case scenario.