0

Hello If i want this text:

$content = '<div id="hey">
   <div id="bla"></div>
</div>

<div id="hey">
 hey lol
</div>';
  • The content inside the id="hey" can be changed.
    And now I want to get the tags in array

    $array[0] = < div id="bla"></div >;
    $array[1] = < hey lol >;
    

How Can I do that? i though about preg_match_all?

3
  • 3
    What is your question exactly? Commented Aug 24, 2011 at 23:59
  • 1
    Based solely off of what you have here, I have two comments. First, you have two divs with the same id... that's bad. Maybe you're looking to use class instead? Second, you could use a regular expression, but since HTML is not a regular language, regular expressions are not ideal. How are you generating these strings, and could you accomplish what you need done some other way? We need more context. Furthermore, I don't even think your example array makes sense, and matching a div inside another one could get wonky. Commented Aug 25, 2011 at 0:10
  • I want to get divs from file_get_content url for example all div id="hey" from url Commented Aug 25, 2011 at 0:16

2 Answers 2

2

Sounds to me, if I understand this correctly, you're looking to parse HTML with PHP. Though regex can work, it's certainly not the best method.

With that said, have a look at the DOMDocument class. It allows you to parse HTML files, and has methods similar to javascript in terms of referencing elements by tag, id, etc.

Per your example:

<?php

$html = '<div id="hey">hey lol</div>'; /* or file_get_contents('...'); */

$dom = new DOMDocument();
$dom->loadHTML($html);

// this will get <div id="hey"></div>
$hey_div = $dom->getElementById('hey');

echo $hey_div->textContent; // "hey lol"
Sign up to request clarification or add additional context in comments.

3 Comments

I was just going to post something like this. Look at stackoverflow.com/questions/2691798/… and php.net/manual/en/class.domdocument.php and that'll probably get OP on the right path.
But If i have more then one <div id="hey">? i tried to to it and it doesn't work.
@Absort: More than one element with the same ID is invalid HTML. You can use $dom->getElementsByTagName('div') and look for those with an id of "hey" though for those kinds of situations, though I'd work on making sure the HTML is valid (if you have control over it). The whole purpose of an id is to be unique across the entire page.
0
$content=str_replace("hey","bla",$content);

OR

$divid="hey";
//$divid="bla";
$content = '<div id="' . $divid . '">
   <div id="bla"></div>
</div>

<div id="hey">
 hey lol
</div>';

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.