Insecure Use of Regular Expressions

Why is this important?

Regular Expressions (Regex) are used in almost every application. However, it is often overlooked that Regular Expressions in PHP can lead to catastrophic outcomes.

Note: This issue only affects applications prior to PHP 7.0.0. The /e modifier is deprecated since 5.5.0 and has been removed with 7.0.0.

Read below to find out how to fix this issue in your code.

Fixing Insecure Use of Regular Expressions

Option A: Use the preg_replace_callback()

  1. Go through the issues that GuardRails identified in the PR.
  2. Locate preg_replace() functions with the /e modifier

    <?php
    $html = $_POST['html'];
    
    // uppercase headings
    $html = preg_replace(
      '(<h([1-6])>(.*?)</h\1>)e',
      '"<h$1>" . strtoupper("$2") . "</h$1>"',
      $html
    );
    
  3. Replace preg_replace with preg_replace_callback:

    <?php
    $html = $_POST['html'];
    
    // uppercase headings
    $html = preg_replace_callback(
      '(<h([1-6])>(.*?)</h\1>)',
      function ($m) {
          return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
      },
      $html
    );
    
  4. Test it

  5. Ship it 🚢 and relax 🌴

More information: