Regex - Greedyness - matching HTML tags, content and attributes

前端 未结 3 853
梦如初夏
梦如初夏 2021-01-28 19: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 s

相关标签:
3条回答
  • 2021-01-28 19:51

    Just adding ? , I think

    /(<span lang="(.*?)">(.*?)</span>)/is
    
    0 讨论(0)
  • 2021-01-28 19:53

    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 !

    0 讨论(0)
  • 2021-01-28 20:04

    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

    0 讨论(0)
提交回复
热议问题