Regex - Greedyness - matching HTML tags, content and attributes

倖福魔咒の 提交于 2019-12-02 14:45:00

问题


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


来源:https://stackoverflow.com/questions/5272604/regex-greedyness-matching-html-tags-content-and-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!