WordPress / WordPress/WordPress-Coding-Standards

Sniff to detect proper usage of preg_quote() ?

Open
#1,371 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Component: Extra Focus: Code analysis Type: Enhancement
Dominant language
PHP
Stars
2.8k
Forks
521
Avg merge
5d 20h
Merged PRs (30d)
1

Description

I'd like to suggest adding two new sniffs around the usage of preg_quote().

  • Verify the $regex parameter of any PCRE function calls to make sure that if the regex is being build up by concatenating parts together, that any $variable parts are wrapped in a call to preg_quote().
    preg_match( '`http[s]?://[^\s<>\'"()]*' . preg_quote( $match_data[0], '`' ) . '`', $content ); // OK.
    preg_match( '`http[s]?://[^\s<>\'"()]*' . $match_data[0] . '`', $content ); // Warning.
    preg_match( $regex, $content ); // OK, ignore as impossible to check reliably.
    
  • Verify that the optional second parameter $delimiter of preg_quote() is always passed.
    Too often I come across code where it is missing and unless it is passed, the default / delimiters are presumed, which is often wrong.

Initially these sniffs would go into Extra, but I'd encourage the WP Core team to consider accepting them into the Core ruleset.

Opinions ?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing how the existing Extra and Core rulesets handle PHP_CodeSniffer sniffs for PCRE function calls. Define checks for concatenated regex variables and for omitted preg_quote() delimiters, then verify the intended warnings against the PHP examples in the issue and determine which ruleset should contain them.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.