Skip to content

Instantly share code, notes, and snippets.

@Potherca
Last active September 6, 2022 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Potherca/294a5b537afafb5fea628c3073e4239f to your computer and use it in GitHub Desktop.
Save Potherca/294a5b537afafb5fea628c3073e4239f to your computer and use it in GitHub Desktop.
🐘🩳 PHP Shorts - Matching URLs or paths regex

ℹ️ This document is part of Potherca's Rules for creating more robust code in PHP

Don't use slash "/" as delimiter when matching URLS or paths

When working with regular expressions (regex) in PHP, it is quite common to use a forward slash (a.k.a. "slash) as delimiter for a regex pattern.

$match = preg_match('/abc/', $subject);

However, when the pattern is a path URL with a path, when a slash / is used as regex delimiter, slashes in the string need to be escaped.

This makes the text harder to parse for humans.

$match = preg_match('/http:\/\/example.com\/api/', $subject);

If another delimiter is used,1 the slash no longer needs to be escaped:

$match = preg_match('#http://example.com/api#', $subject);

This also makes it more clear whether any trailing slash is a delimiter or part of the match pattern.

Footnotes

  1. Often used delimiters are forward slashes (/), hash signs (#) and tildes (~).

    ↩
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment