2

I have this part of an html page:

<td>
  <div class='medals gold'> 
    </div> 
</td>

To extract and print to video the div attribute I used this php code:

$div = $result->getElementByTagName('div');
echo $div->getAttribute('class') . " ";

In this way I get the string medals gold.

Could I extract indeed only the substring gold? It would be perfect.

0

3 Answers 3

1

You could use preg_split and split the string on the empty space as others suggest

/* it should be `getElementsByTagName`*/
$div=$result->getElementsByTagName('div')->item(0);

list( $junk, $keep )=preg_split('@\s@',$div->getAttribute('class') );
echo $keep;

/* or */
$divs=$result->getElementsByTagName('div');
foreach( $divs as $div ){
    list( $junk, $keep )=preg_split('@\s@', $div->getAttribute('class') );
    echo $keep;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the explode function to split the string medals gold into an array of two strings array('medals', 'gold'):

$div = $result->getElementByTagName('div');
$parts = explode(' ', $div->getAttribute('class'));
echo $parts[1];

3 Comments

split function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.
updated the answer to something that actually works. Sorry about that.
I get this error: Parse error: syntax error, unexpected '[', expecting ',' or ';'
0

Since split function was DEPRECATED in PHP 5.3, and it is also REMOVED in PHP 7.0, so I would suggest you to use explode.

Also

  • explode() is substantially faster because it doesn't split based on a regular expression, so the string doesn't have to be analyzed by the regex parser
  • preg_split() is faster and uses PCRE regular expressions for regex splits

So, it would be better option :

$div = $result->getElementByTagName('div');
$parts = explode(' ', $div->getAttribute('class'));
echo $parts[1];

where you'll get array with 2 strings. //array('medals', 'gold')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.