siniradam siniradam - 2 years ago 132
PHP Question

Selecting specific html tag which contains specific word with regex

From a full of html codes, i want a specific html tag which contains a specific word.

<textarea>asdasdasdasd as</textarea>
<textarea>asdasdasdasd as</textarea>

This is returns content between first textarea and last /textarea tag but desired result is at the middle.


wrong result

Expected result;


I've tried a couple things more but I couldn't make it work as multiline.
enter image description here
How can I achieve that?

Jan Jan
Answer Source

You have different possibilities here.

The regex version

<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>

This uses a technique called the tempered greedy token, see a demo on

Xpath queries

Another one would be to use xpath queries, ie:

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

Afterwards, do whatever you want with the elements (ie remove them from the DOM).


Your original query with [ccc] will certainly not do what you expect it to - it is a character class which is redundant in this case (c will do the same).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download