-1

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.

matt
  • 2,312
  • 5
  • 34
  • 57

2 Answers2

1

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)

Tim S.
  • 13,597
  • 7
  • 46
  • 72
  • @ITroubs There's the `U` modifier which makes the regex ungreedy as well. However, I prefer this way. (http://php.net/manual/en/reference.pcre.pattern.modifiers.php) – Tim S. Mar 21 '13 at 16:18
  • 1
    yeah it is better this way because you can actively controll what is greedy and what isn't – ITroubs Mar 21 '13 at 16:27
1

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.