siniradam siniradam - 5 months ago 20
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>asdacccda
sdas</textarea>
<textarea>asdasdasdasd as</textarea>


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

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


wrong result

Expected result;

<textarea>asdacccda
sdas</textarea>


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

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 regex101.com.


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


Hints

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