help making an array

Discussion in 'PHP' started by Brinked, Aug 20, 2008.

  1. #1
    I need help with making something into an array. the following code:

            $tagname = "h1";
            $pattern = "/<$tagname>(.*?)<\/$tagname>/";
            	preg_match_all($pattern, $content, $matches); 
        
    		foreach ($matches[1] as $match)
    {
    	$match = rtrim($match);
        	$jump = "<a href=\"#$match\"><b>" . $match . "</b></a> | ";
    		print str_replace(array(":","<br />"), "",$jump);
    
    }
    PHP:
    What it does is searches the page content for all text found between <h1></h1> tags and makes them into jumplinks.

    This works fine however I would like to make it an array so I can include other tag types such as h2, h3 etc.

    I tried making $tagname = "h1"; into $tagname =array( "h1", "h2", "h3");

    but that didnt work out.
     
    Brinked, Aug 20, 2008 IP
  2. Christian Little

    Christian Little Peon

    Messages:
    1,753
    Likes Received:
    80
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $tagnames = array ("h1", "h2", "h3");
    foreach($tagnames as $tagname) {
    //paste your code here
    }

    if it doesn't work change the second line to: foreach($tagname as $tagnames) {

    I can never remember which order to put stuff in the foreach statement :)
     
    Christian Little, Aug 20, 2008 IP
  3. jack_ss

    jack_ss Guest

    Messages:
    94
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It would be:
    foreach($tagname as $tagnames)
    foreach (array as $value)
        statement
    foreach (array as $key => $value)
        statement
    PHP:
    dig it.
     
    jack_ss, Aug 20, 2008 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    No need for extra loops...
    
    $tagname = "(h[123])";
    $pattern = "~<$tagname>(.*?)</\1>~si";
    
    foreach ($matches[2] as $match)
    // ....
    
    PHP:
     
    nico_swd, Aug 21, 2008 IP