I have got as far as page 250, and am having a problem understanding the example of preg_replace. I don’t understand how (.*), when applied to ‘banana’ can possibly result in ‘ba’; when used on its own it would produce ‘banana’. Can someone please take me slowly through how the text will result in the output of ‘nanaba’?
I don’t have your copy of the book handy. But if you post the code in question I’ll try to help.
This would be because you haven’t read the entire expression. Or the paragraph underneath the expression in which Kevin outlines exactly what part matches to what and how you get the resultant output.
The expression, in full, is “/(.*)(nana)/”.
Which in full english means: Delimiter /, Capture as the first subpattern [()'s] Any number of non-newline characters, followed by the subpattern containing 4 characters ‘nana’, End Delimiter.
PHP looks at the input string “banana” and says: "Okay, I can match that pattern if .* = “ba”, since the rest is “nana”.
Preg_replace says “Okay, take that, and now replace it with…”
In the book, Kevin’s explaining backreferencing, and so his replacement string is “$2$1”, which is read as “The second sub-pattern matched, followed by the first subpattern matched.”
The second subpattern is the “nana”, and the first subpattern is the “ba”, so… nanaba.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.