开发者

Difference between # and / in preg_replace function for pattern parameter?

What does the # sign do differ开发者_运维技巧ently than the /?

$output = preg_replace('#[^A-Za-z0-9]#i', '', $input);
$output = preg_replace('/[^A-Za-z0-9]/i', '', $input); 

And what does the letter i do after /[^A-Za-z0-9]/?

Also what does the ^ mean?


In some languages, it does not matter what type of character starts or ends the pattern portion of the regular expression, so long as it is the same at the beginning and the end (I believe this is a holdover from Perl, arguably the first great regex language). Since PHP follows this line of thought, # and / are equivalent.

  • i = "Make this search case insensitive"
  • [^...] = exclude everything between the square brackets (^ basically means "exclusion" in this context).

You can learn a lot about regular expressions here.


It's just a different delimiter. If you're going to be using slashes in your regex a lot, you don't want to have to escape it every time, so you assign a hash (or another character, there are plenty to choose from) as the delimiter so that it doesn't need to be escaped.

The i at the end of the regex is a modifier telling PHP to disregard case when performing the match. i.e. the characters A and a are equivalent. When using the i modifier, there's no need to use A-Za-z since a-z is included as part of the caseless A-Z match.

The carat (i.e. ^), when used as the first character in a character list, means to match anything that is not in that list). So [^abc] matches anything but the characters a, b, and c.


^Matches the starting position within the string. In line-based tools, it matches the starting position of any line. you can use this tool in javascript to see differences:

these are very important in regex '*', '+', and '?', which denote the number of times a character or a sequence of characters may occur.

'*' means "zero or more"

'+' means "one or more"

'?' means "zero or one"

Also I like this tutorial

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜