字符串的正则表达式(图像url检查)


Regular expression for a string (image url checking)

我需要正则表达式,因为字符串是图像url。我需要三种类型的正则表达式

  1. 以斜线开头(例如:/p/230x230/9/Apple_iPad_2_16GB@@9ap4d206.png)
  2. 以双斜线开头(例如://image)
  3. 以http开头(例如:'http://....')

您可以使用这个:

$pattern = '~(?>https?+:/|/)?(?>/[^/'s]++)+~';

解释:

(?>           # open an atomic group *
    https?+   # http or https
    :/        #
   |          # OR
    /
)?            # close the atomic group and make it optional
(?>           # open an atomic group
    /
    [^/'s]++  # all characters except / or spaces one or more times (possessive *)
)+            # close the atomic group, one or more times

(*有关所有格量词和原子群的更多信息。)

注意:

由于该模式描述了一个充满斜杠的url,所以我使用~作为分隔符,而不是经典的/。因此,斜杠不需要在模式中转义。

您可以向该模式添加锚点,以确保从开始到结束都与您的字符串完全匹配:

$pattern = '~^(?>https?+:/|/)?(?>/[^/'s]++)+$~';