rman Posted March 17, 2015 Share Posted March 17, 2015 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. Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 17, 2015 Share Posted March 17, 2015 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>/'; Quote Link to comment Share on other sites More sharing options...
rman Posted March 17, 2015 Author Share Posted March 17, 2015 Psysco Thank you for your post. I have used that pattern before and it only returns links. The pattern in the code I gave does give some div tags but does not give the whole tag. Any other suggestions would be appreciated. Thanks again, r. Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 17, 2015 Share Posted March 17, 2015 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 ) ) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.