Beginner PHP help needed

跟風遠走 提交于 2019-12-11 02:10:28

问题


I have been learning PHP for some time now and I wanted one clarification.

I have seen the preg_match function called with different delimiting symbols like:

preg_match('/.../')

and

preg_match('#...#')

Today I also saw % being used.

My question is two part:

What all characters can be used?

And is there a standard ?


回答1:


Any

  • non-alphanumeric
  • non-whitespace and
  • non-backslash ASCII character

can be used as delimiter.

Also if you using the opening punctuation symbols as opening delimiter:

( { [ <

then their corresponding closing punctuation symbols must be used as closing delimiter:

) } ] >

The most common delimiter is /.
But sometimes it's advised to use a different delimiter if a / is part of the regex.

Example:

// check if a string is number/number format:
if(preg_match(/^\d+\/\d+$/)) {
  // match
}

Since the regex contains the delimiter, you must escape the delimiter found in the regex.

To avoid the escaping it is better to choose a different delimiter, one which is not present in the regex, that way your regex will be shorter and cleaner:

if(preg_match(#^\d+/\d+$#)) 


来源:https://stackoverflow.com/questions/4352377/beginner-php-help-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!