选择包含正则表达式

时间:2016-06-24 13:06:02

标签: php regex

从完整的html代码中,我想要一个包含特定单词的特定html标记。

<textarea>asdasdasdasd as</textarea>
<textarea>asdacccda 
sdas</textarea>
<textarea>asdasdasdasd as</textarea>

这是返回第一个textarea和last / textarea标签之间的内容,但是期望的结果位于中间。

\<textarea\>(.*)[ccc](.*)\<\/textarea\>/s

wrong result

预期结果;

<textarea>asdacccda 
sdas</textarea>

我尝试过更多的东西,但我不能让它像多线一样工作。 enter image description here 我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

这里有不同的可能性。

正则表达式版本

<textarea>                  # match <textarea>
(?:(?!</textarea>)[\s\S])*? # match anything but stop before </textarea>
ccc                         # the word you want
(?:(?!</textarea>)[\s\S])*? # same construct as above
</textarea>                 # match </textarea>

这使用了一项名为tempered greedy token的技术,请参阅a demo on regex101.com

<小时/>

Xpath查询

另一个是使用xpath查询,即:

//textarea[contains(., 'ccc')]

然后,用元素做任何你想做的事情(即从DOM中删除它们)。

<小时/>

提示

使用[ccc]的原始查询肯定不会达到预期效果 - 在这种情况下,它是一个多余的字符类(c也会这样做。)

答案 1 :(得分:1)

这是一个有效的正则表达式:

<textarea>((?:(?!<\/textarea>).)*?)ccc(.*?)<\/textarea>

是的,这似乎相当不太重要,但这可以追溯到为什么使用正则表达式来处理HTML内容并不是最好的主意。这是细分:

<textarea>((?:(?!<\/textarea>).)*?)ccc(.*?)<\/textarea>
<textarea>  -- literal match of text
          (                       )  -- your original capturing group
           (?:(?!<\/textarea>).)  -- this is a bit tricky but the idea is that you dont want it to match the textarea as part of the group
                                 ? make this token non greedy
                                   ccc   -- literal match of 3 c's, dont use square brackets, thats for doing a "one of the things in these brackets" match
                                      ( .. . . . . . >     -- this can stay the same

如果您想在regex101上看到它,请参阅here

相关问题