Jump to content

preg_match_all question


N-Bomb(Nerd)

Recommended Posts

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?

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.