Jump to content

[SOLVED] getting contents between tags in string and output them one by one?


Sam Granger

Recommended Posts

Hey!

 

I have a pdf class, and I can use it to output images. I want to get info from the database. The content could look like this for example:

text text text, more text [image]hello.jpg[/image] haha hello [thumb]hi.gif[/thumb]. haha more text

 

Anyway, you get the point :).

 

How do I get the contents out of the tag and put them into images? I think array? or?

 

I need to use a seperate code for text and images to generate the pdf. :)

 

For text:

$pdf->ezText("$title", 22);

 

And for images:

$pdf->ezImage('http://www.domain.com/logo.jpg', '0', '150', 'none', 'left');

 

for each image.

 

Help! :(

 

Do I use preg_match?

This should do what you need. It will strip out all the tags and populate them into an array. It won't handle nested tags though. I also added in some basic whitespace handling to help make the returned text look better.

 

<?php
  function matchCallback ( $matches ) {
    global $tags;
    list(,$tag,$contents,$suffix) = $matches;

    //Add Tag
    if(!isset($tags[$tag])) $tags[$tag] = array();
    $tags[$tag][] = $contents;
    
    //Make replacement
    $rVal = '';
    return (preg_match('/[a-zA-Z0-9]/',trim($suffix)))
      ? ' '.trim($suffix) //Found a charachter, add a space
      : trim($suffix); //Found something else, no space
  }

  $text = "text text text, more text [image]hello.jpg[/image] haha hello [thumb]hi.gif[/thumb]. haha more text";
  $tags = array();
  $text = preg_replace_callback('/\s*\[(\w+)\](.+?)\[\/\1\](\s*.?)/',matchCallback,$text);
  print_r($tags);
  print $text;
?>

<?php
...
  $text = "text text text, more text [image]hello.jpg[/image] haha hello [thumb]hi.gif[/thumb]. haha more text";
  $tags = array();
  $text = preg_replace_callback('/\s*\[(\w+)\](.+?)\[\/\1\](\s*.?)/',matchCallback,$text);

  //Go through all of them
  foreach($tags as $tagname=>$items){
    print "<b>{$tagname}</b><ul>";
    foreach($items as $item)
      print "<li>{$item}</li>";
  }

  //Just image tags
  if(is_array($tags['image'])){
    foreach($tags['image'] as $item)
      $pdf->ezImage($item, '0', '150', 'none', 'left');
  }
?>

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.