Home > Back-end >  A regular expression to search for a tag that contains any substring
A regular expression to search for a tag that contains any substring

Time:04-21

For example: there are some text:

<script>blablablaNEEDLEblablabla</script><script>blablablalablabla</script>

I want to find tag if it contains "NEEDLE"

What I expect in output:

blablablaNEEDLEblablabla
<script.*\s.*needle.*\s.*script>/im

That regular works fine in Regex101, bit dont wort in PHP (preg_*)

CodePudding user response:

That regular works fine in Regex101

No, that doesn't work in https://regex101.com/r/8nObIl/1 because of the \s for whitespace. In your example, there is no whitespace.

To capture what you want, use a capture group (). Also, you probably want to modify it for tags like <script type="blah"> so you don't get that.:

preg_match('~<script[^>]*>(.*needle.*)</script>~im', $content, $match);
  • Related