N-Bomb(Nerd) Posted June 14, 2009 Share Posted June 14, 2009 I have the following: preg_match_all('~secret stuff here~', $string, $arr); Why can't I simply echo $arr[2] to out the element I want? Quote Link to comment https://forums.phpfreaks.com/topic/162128-preg_match_all-question/ Share on other sites More sharing options...
N-Bomb(Nerd) Posted June 14, 2009 Author Share Posted June 14, 2009 Using this outputs "array" instead of the actual vaule of the element. echo $arr[2]; How can I output the value of $arr[2]? Quote Link to comment https://forums.phpfreaks.com/topic/162128-preg_match_all-question/#findComment-855548 Share on other sites More sharing options...
N-Bomb(Nerd) Posted June 14, 2009 Author Share Posted June 14, 2009 I guess I didn't pick the best title for this.. Quote Link to comment https://forums.phpfreaks.com/topic/162128-preg_match_all-question/#findComment-855563 Share on other sites More sharing options...
wildteen88 Posted June 14, 2009 Share Posted June 14, 2009 Using this outputs "array" instead of the actual vaule of the element. echo $arr[2]; How can I output the value of $arr[2]? You saying when echo'ing the variable $arr[2] you get Array as the output? In that case $arr[2] contains an array. To see the contents of an array you should use print_r. Like so echo '<pre>'. print_r($arr[2], true) .'</pre>'; Whats the output? Quote Link to comment https://forums.phpfreaks.com/topic/162128-preg_match_all-question/#findComment-855595 Share on other sites More sharing options...
.josh Posted June 14, 2009 Share Posted June 14, 2009 which (sub)array/element of $arr your stuff will be in depends on the regex. $arr[0] always contains the full regex match. $arr[1] contains the first full captured match (the regex within parenthesis). $arr[2] would have the matches from the 2nd capture, etc.. Consider the following string: $string = "<a href='blah'>something</a>"; //This will only return $arr[0] and that will contain the whole string. preg_match_all("~<a[^>]*>.*?</a>~",$string,$arr); // $arr[0] : <a href='blah'>something</a> // This will return $arr[0] and $arr[1] preg_match_all("~<a[^>]*>(.*?)</a>~",$string,$arr); // $arr[0] : <a href='blah'>something</a> // $arr[1] : something // This will return $arr[0] and $arr[1] and $arr[2] preg_match_all("~<a href='([^']*)'[^>]*>(.*?)</a>~",$string,$arr); // $arr[0] : <a href='blah'>something</a> // $arr[1] : blah // $arr[2] : something Quote Link to comment https://forums.phpfreaks.com/topic/162128-preg_match_all-question/#findComment-855604 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.