Regex - Greedyness - matching HTML tags, content a

2020-04-30 18:24发布

问题:

I am trying to match specific span-tags from an HTML source.

The lang-attribute and the inner HTML of the tag are used as parameters for a function which returns a new string.

I want replace the old tags, attributes and content with the result of the called function.

The subject would be something like this:

<p>Some codesnippet:</p>
<span lang="fsharp">// PE001
let p001 = [0..999]
           |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0)
           |> List.sum
</span>
<p>Another code snippet:</p>
<span lang="C#">//C# testclass
class MyClass {
}
</span>

In order to extract the value of the lang attribute and the content, I group those values with the following expression:

/(<span lang="(.*)">(.*)</span>)/is

Since regex tends to be greedy, This expression matches the complete subject, not just one span-tag and its content.

How do i manage to match just one span-tag?

回答1:

We'll never reapeat it again : do not use regular expressions to work with HTML !


Instead, use DOMDocument::loadHTML.

It'll allow you to manipulate your HTML data using the DOM, which is much more powerful and easier : you'll be able to :

  • Use methods such as getElementById and getElementsByTagName for simple extractions,
  • Use the DOMXPath class to make XPath queries on your document
  • Work with DOMElements, and methods such as getAttribute / setAttribute
  • ...

Really : take the time to learn DOM : it's a great investment !



回答2:

You can specify it to be ungreedy using ?

/(<span lang="(.*?)">(.*?)<\/span>)/is

or make all expression ungreedy by default using PCRE_UNGREEDY modifier

/(<span lang="(.*)">(.*)<\/span>)/Uis



回答3:

Just adding ? , I think

/(<span lang="(.*?)">(.*?)</span>)/is