Jump to content

Print out div tags with content.


rman

Recommended Posts

I am a beginner in PHP. I am working with regex in a form where it will display all div tags with content. I am having touble displyaing the div tags. I have looked on the internet and haven't found what I need. Most want to use DOM and I get that but I want to use regex instead. I am trying to understand the regex. If any one can can help I would appreciate it. I believe the area I am having trouble with is the pattern match. I did get some information from PHP site

 

Thanks;

r

 

Here is the area  of code I think needs changing:

 while(!feof($fp)) {
          $line = fgets($fp);

	  $pattern = '/[<div>](.*?)(<\/div>)/';
          $matches = preg_match_all($pattern, $line, $found);
	 if ($matches >= 1 ) {
             echo $found[1][0] . "\n";

          }  
      }

I also have use /<\s*div[^>]*>(.*?)<\s*\/\s*div>/ and /<div[^>]++>(.*?)<\/div>/s. But they did not work either.

Link to comment
https://forums.phpfreaks.com/topic/295326-print-out-div-tags-with-content/
Share on other sites

Do you realize that if the opening and closing div tags are not on the same line it won't find them if you are only processing one line at a time? Plus, you have the added problem of DIV tags that are within other div tags. That is why RegEx is not a good solution for this. Plus, what if the div tag has paramters, e.g. <div class="something">?

 

So, it would get really complicated to get a good solution with RegEx. But, based on what you are trying to do, this would work better

 

$pattern = '/<div>(.*?)<\/div>/';

Perhaps you should provide some example strings that are not providing the results you expect. The code I provided works exactly as expected based upon the requirements you provided

 

 

$line = "This is <div>some text</div> with a <div>div tag</div> in it.";
 
$pattern = '/<div>(.*?)<\/div>/';
$matches = preg_match_all($pattern, $line, $found);
echo "<pre>" . print_r($found, 1) . "</pre>";

 

Output:

 

Array
(
    [0] => Array
        (
            [0] => <div>some text</div>
            [1] => <div>div tag</div>
        )
 
    [1] => Array
        (
            [0] => some text
            [1] => div tag
        )
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.