0

Am new to Regex & working through examples to clarify my understanding. PHP functions site gives an example for the preg_filter function, which I do understand fully - except for one thing:

$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4'); 
$pattern = array('/\d/', '/[a-z]/', '/[1a]/'); 
$replace = array('A:$0', 'B:$0', 'C:$0'); 

gives for $replace:

Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)

So far so good - I understand why elements [5] & [6] aren't returned, & why elements [2] - [7] display the values they do. Where I get confused is with elements [0] & [1].

I was expecting return values of A:1C:1 & B:aC:a respectively, as each matched pattern is replaced with the 'capital letter:' & the capture referenced value.

So I am wondering what aspect of Regex (I'm still very new to this) I'm missing given the actual result displayed.

Any assistance would be gratefully received.

Thanks

  • It looks like you do not understand what `/[1a]/`=> `'C:$0'` does, right? Why do you think *each matched pattern is replaced with the 'capital letter:' & the capture referenced value*? – Wiktor Stribiżew Oct 01 '17 at 20:19
  • My thinking is based on a guess (Idid mention I was new to Regex). The later matched elements return 'A' if a digit, or 'B' if alpha numeric, the ':' & the element's value. If you know thw answer to this please just provide it - why does trying to find out why I don't understand something have to take precedence? I'm new, I'm trying to learn - that;s why I ask questions about things I don't understand, I don't pshyco-analysis as to why I don't understand yet - its because I'm now to this subject. – Paracelsus Oct 01 '17 at 20:29
  • I had an answer typed out already, but the question got closed; so you get a comment instead: the regexps change the elements of the $subject array when they match. This means that the third regexp sees the elements as modified by the earlier ones. For the first element, the "1" becomes "A:1", and then the third regexp finds the "1" in this string, and replaces that with "C:1", producing "A:C:1" – Bass Oct 01 '17 at 20:31
  • See https://regex101.com/r/VZhT7C/1, there is no need for an answer. Just keep in mind regexp replacements are done one after another with `preg_filter`. – Wiktor Stribiżew Oct 01 '17 at 20:31
  • Thnak you Bass - now understand fully. Appreciated. – Paracelsus Oct 01 '17 at 20:36

0 Answers0