开发者

Regex - Greedyness - matching HTML tags, content and attributes

开发者 https://www.devze.com 2023-02-16 01:10 出处:网络
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 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开发者_Python百科-tag?


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 !


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


Just adding ? , I think

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号