Shortdark Software Development

Regex Examples

Development19th Jul 2020.Time to read: 1 min

Regex

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.


Previous: Some CSS DiscussionNext: PHP Coding Style (More Than One Way to Skin a Cat)