Welcome to Abdul Malik Ikhsan's Blog

Practical Regex 1: Using Named Capturing Groups

Posted in regex, tips and tricks by samsonasik on September 3, 2021

Still using numbered group of capture value in Regex? You may forget, or the index changed if the requirement changed. For example, you want to get a csrf value from a form field with the following regex example:

name="csrf" value="(.{32})"

For input field csrf with 32 chars value “4X0ZfDKr71KHCec7SOkoJ5onq1PTCN3v”, you want to get the value, you will need to get index 1 for it with PHP:

<?php

$pattern = '#name="csrf" value="(.{32})"#';
$content = <<<'HTML_CONTENT'
<form>
    <input type="hidden" name="csrf" value="4X0ZfDKr71KHCec7SOkoJ5onq1PTCN3v" />
    <input type="submit" />
</form>
HTML_CONTENT;

preg_match($pattern, $content, $matches);
if ($matches !== []) {
    echo $matches[1];
}

To handle the possible forgotten index or changed index that can create a bug, you can use named capturing groups, so you can change to:

name="csrf" value="(?<csrf_value>.{32})"

Now, you can get it easily:

<?php

$pattern = '#name="csrf" value="(?<csrf_value>.{32})"#';
$content = <<<'HTML_CONTENT'
<form>
    <input type="hidden" name="csrf" value="4X0ZfDKr71KHCec7SOkoJ5onq1PTCN3v" />
    <input type="submit" />
</form>
HTML_CONTENT;

preg_match($pattern, $content, $matches);
if ($matches !== []) {
    echo $matches['csrf_value'];
}

That’s it 😉

Ref: https://www.regular-expressions.info/named.html

One Response

Subscribe to comments with RSS.

  1. […] if the code is getting more complex, like in my previous post for named capturing group, you need to remember the numbered index! To handle it, you can use named backreference for it, so […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: