HomeWho We AreContact

Regex Examples

By Neil Ludlow
Published in Development
July 19, 2020
1 min read
Regex Examples

Coding that is simple yet powerful allows you to get many different problems solved. As such, using regex is one of my favorite coding methods. In PHP you might use it in a preg_match or preg_replace but regex can be used in many different programming languages although it can sometimes be slightly different from language to language.

Regex101 is a good place to try out regex before inserting it into your code.

Negative lookaheads

You might have a pair of tags and instead of using PHP’s strip_tags() function you might want to do something a bit more custom with regex.

To get everything within specific tags you could do something like this, which assumes there aren’t going to be any other tags within the tag you’re looking for…

<code><tag>([^<]*)<\/tag></code>

You’re looking for a <tag> then anything except a < then a </tag. Putting it inside brackets () makes it a capturing group.

If you thought there was a possibility there would be other “h1” or “p” tags inside your tags you would need to be more specific, possibly using a negative lookahead like…

<code><tag>((?!<\/tag>).*)<\/tag></code>

This time (?!<\/tag>).* means that you are looking for anything that isn’t </tag> which means that another tag with a different name is not going to affect it.

But, even this is not perfect. If you had two tags with the name “tag” nested within each other this might not give you the answer you were looking for.

More information on negative and positive lookaheads, lookbehinds and lookarounds here.


Tags

#regex

Share

Previous Article
CSS Discussion
Neil Ludlow

Neil Ludlow

Freelance Software Developer

Related Posts

Choosing a Tech Stack in 2024
September 16, 2024
5 min
© 2024, All Rights Reserved.
Powered By

Quick Links

About ShortdarkContact

Legal Stuff

Social Media