简体   繁体   中英

Regular expression in php to search url with a given pattern

I want to search a given text for local URLs in link's href attributes, using regular expression. Currently, I have this regular expression:

'/href=["\']?([^"\'>]+)["\']?/'

Now, I'd like to add some more filtering: Only get those links, which start like this:

XXXX-XX-XX

Where X is a number. This should match this: 2015-05-15/ , 2015-05-15_03_21_32/ and also 2014-12-21 (any date set by me).

You can use the following regex:

href=["']?(\d{4}(?:[-_]\d{2})+)["']?

PHP: $re = "#href=[\\"']?(\\d{4}(?:[-_]\\d{2})+)[\\"']?#";

Explanation:

  • href=["']? - matches href= and an optional single or double quote
  • (\\d{4}(?:[-_]\\d{2})+) - a capturing group around the href attribute value
    • \\d{4} - Exactly 4 digits
    • (?:[-_]\\d{2})+ - 1 or more groups of - / _ + 2-digit numbers
  • ["']? - matches an optional single or double quote

See Regex demo here and IDEONE demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM