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); Link to comment https://forums.phpfreaks.com/topic/244410-re-stuck-with-preg_replace/ 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. Link to comment https://forums.phpfreaks.com/topic/244410-re-stuck-with-preg_replace/#findComment-1255309 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 Link to comment https://forums.phpfreaks.com/topic/244410-re-stuck-with-preg_replace/#findComment-1255349 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.