kcp88 Posted August 10, 2011 Share Posted August 10, 2011 Hi can someone explain this code to me ? I really don't understand ..... preg_replace('/([a-zA-Z]).*/', '$1', $variable); Quote Link to comment Share on other sites More sharing options...
Morg. Posted August 10, 2011 Share Posted August 10, 2011 I don't understand it either and I use regex every day, use google, type regex, read up and translate. GL. Quote Link to comment Share on other sites More sharing options...
.josh Posted August 10, 2011 Share Posted August 10, 2011 all by itself it effectively does nothing, since the returned result of the preg_replace isn't being assigned to anything. At a minimum, you would have to assign it to a variable, or echo it out, or something. Point is, the original variable $variable (3rd argument in the function) isn't altered. Example: echo "before: " . $variable . "<br/>"; $variable = preg_replace('/([a-zA-Z]).*/', '$1', $variable); echo "after: " . $variable; The regex itself basically finds the first instance of a letter (case-insenstive) and removes everything after it. breakdown of the regex /([a-zA-Z]).*/ / Starting pattern delimiter ( Start of captured group 1 [a-zA-Z] Character class to match 1 of any lowercase or uppercase letter ) End of captured group 1 .* Greedy match of 0 or more of any character (other than newline character) / Ending pattern delimiter replace all that was match with... $1 whatever was captured in group 1 Examples (green is what is matched and captured by capture group 1, red is what is matched by the .*): $variable = "abc" before: abc after: a $variable = "123 Abc blah"; before: 123 Abc blah after: 123 A Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.