Jump to content

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


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');
  }
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.