Jump to content

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
        )
)
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.