tags:

views:

70

answers:

2

hi

im new to regular expressions and would like to decipher this.

return preg_replace("/[<>]/", '_', $string);

thanks!!

+9  A: 

It means "replace each < or > inside the string $string with an underscore, then return the result".

The slashes (/) delimit the regular expression. You can use other characters instead (preg_replace("#[<>]#", '_', $string); would work just as well and makes sense if your regex contains a slash itself).

[] brackets denote a character class. They mean essentially "one character of those contained within the class", so [<>] means "either a < or a >".

You can also negate a character class by starting it with a ^: [^<>] means "any character except < or >.

Tim Pietzcker
Beat me by 30 seconds. Just glad my answer was right. :P
spinon
thanks that's very helpful, the only thing i dont get is whats the point of using the / at the start and end of the argument, (or # as you show in the example) , would the function not work by simply using "[<>]" thanks!
chicane777
It wouldn't work since PHP requires the use of regex delimiters. I can't tell you why though - other languages have implemented this differently. Python or .NET use strings (without additional delimiters), Ruby has regexes as first-class objects so they need their own delimiter (`/`). In JavaScript you can choose to build a regex using a string (`"..."`) or a regex object (`/.../`). Why you need both in PHP - no idea.
Tim Pietzcker
ok great, thanks for the help you are very knowledgable
chicane777
A: 

It looks like it is replacing either the greater than or the less than sign with an underscore. But I am a little rusty in regex

spinon