Solved

Matching HTML for replacing with regexp.

Posted on 2009-04-07
2
173 Views
Last Modified: 2012-05-06
Hello,

I'm having some trouble doing some specific matching on a string containing a complete HTML page.

The case is as follows: Given specific headings, I am to find those headings and remove them and the text below them.

So far I've got the matching of the headings working nicely. The problem comes when I'm looking to match the text below them. I'm having trouble making it stop as it were.

My idea is to look for the next <h#> tag and match to it. However, it doesn't stop at the *next* tag, it stops at the *last* one, and thus the script removes a lot more than it should. How do I prevent this?
$needle = '/<h'.$overskrift['Level'].'> <span class="mw-headline">'.str_replace('/', '\/', $overskrift['Heading']).'<\/span><\/h'.$overskrift['Level'].'>.*(<h\d>)/s';
 
// Example value of $needle: /<h2> <span class="mw-headline">Heading<\/span><\/h2>.*(<h\d>)/s
// Works nicely up till the dot.
 
$res = preg_replace($needle, "$1", $res);

Open in new window

0
Comment
Question by:Elisas
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 18

Accepted Solution

by:
Hube02 earned 250 total points
ID: 24086517
the problem is that preg funcntions are gready and will match as much as they can. you can turn off this greadyness by adding a ?

.*?(<h\d>)

Let me know if this works, if not then we will try a lookahead here.
0
 

Author Closing Comment

by:Elisas
ID: 31567458
Superb. That did the trick.
0

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question