Jump to content

[SOLVED] get content from specific tags


julia k

Recommended Posts

Hi!

 

I am looking for a way of getting some text content from specific tags.

 

Right now I have a comment submission form that sends data to a database. After the comment was submitted, I need it to be displayed in the comments page under a specific post. I managed to do that and the damn thing works, only that in comments a member can post some code samples too (in code tags) which I'd like to highlight using the Geshi class and this is where I got stuck...So I was wondering how to get the content of these code tags (if one would exists, of course) and then remove the code tags but keep all others.

 

This is a simple example of how a comment might look like:

 

< p >Some text - text - text< /p >

< p >Some text - text - text< /p >

< code >

      // this is a sample script

      <? php

              $data = '';

              $example = 'test';

      ?>

< /code>

< p > This paragraphs should be displayed as paragraphs...< /p>

 

In the above example there is only a code tag only that there could be more of them so I'll need a method to parse them all...

 

Anyone has any idea about how to do this?

 

Thank you in advance for any hints or solutions :)

Link to comment
Share on other sites

I've kept trying different aproaches before you posted that code, and the one that came close to the truth is this one:

 

        $c_content    = decode($_comment['comment_content']);

        preg_match_all( "/<code>(.*)<\/code>/si", $c_content, $match );
        if (is_array($match[0]) and count($match[0]) >= 1)
        {
            foreach ($match[0] as $m)
            {
                $x = str_replace('<code>', '', $m);
                $y = str_replace('</code>', '', $x);
                $z = str_replace($m, $y, $c_content);
        
                // SET UP GESHI
                $geshi = new GeSHi($z, $lang, GESHI_LANG_DIR);
                $geshi->set_header_type(GESHI_HEADER_PRE_VALID);
                $c_content = str_replace($z, $geshi->parse_code(), $z);
            }
        }
$output .= $start_content .$c_content. $end_container ;

 

the above code reside in a function (I'm using smarty) and the content of the $output variable will display the comment on the page. The problem with that code is that if I have any other paragraphs between the <code> tags they will also be interpreted by geshi and will be highlighted...I think the problem is inside the str_replace...I don't know...I hate that!

 

i tried the code you posted too, only that when viewing the comment it will be displayed as pure html (like using htmlentities) and also it gets highlighted by geshi...what am I doing wrong here??

 

Link to comment
Share on other sites

Done!

 

I've found my answer after a lot of trial and error, and I'll post my solution here just in case someone else would be looking for something like this in the future:

 

 

// Objective:

Highlight the code samples posted in a comment using the Geshi class.

 

// Implementation:

In a function that returns the output instead of printing it right away.

 

 

// the function (excerpt)

<?php
/**
*    Display comments for a given post
*
    UASAGE:
===============================================
    {list_comments    loop = $comments_to_show }
*/
function smarty_list_comments($params)
{
    # Arguments:
    $comments     = $params['loop'];


    // all comments will be displayed in a div: [ class = comment_wrapper ]
    $start_container     = '<div class="comment_wrapper">';
    $start_header        = '<div class="comment_wrapper_header">';
    $start_content        = '<div class="comment_wrapper_body">';
    $start_footer        = '<div class="comment_wrapper_footer">';
    $end_container      = '</div>';
    $output               = '';    // leave empty


    // if there are no comments yet
    if (count($comments) < 1)
    {
        $output = '<p class="no_data">There are no comments for this post.</p>';
        return $output;
    }


    foreach ($comments as $_comment)
    {
        /*==========================================
        //                PREPARE DATA
        ==========================================*/

        $c_id        = $_comment['comment_id'];
        $c_content    = decode($_comment['comment_content']);
        $lang        = $_comment['geshi_alias']; // gets the lang name

        /*
        *    If there is a code in the comment, select it for highlighting
        */
        // >> start
        $codes = array();
        $matches = getContentFromTags($c_content);

        $i=0;
        while ( $i < count($matches) )
        {
            // strip code tags:
            $tags_to_remove = array('<code>','</code>');
            $matches[$i] = str_replace($tags_to_remove, '', $matches[$i]);

            $codes[] = htmlentities($matches[$i], ENT_QUOTES, 'UTF-8');
            $i++;        
        }
    
        for ( $i = 0; $i < sizeof($codes); $i++ )
        {
            // SET UP GESHI
            $geshi = new GeSHi(decode($codes[$i]), $lang, GESHI_LANG_DIR);
            $geshi->set_header_type(GESHI_HEADER_PRE_VALID);
            $c_content = str_replace(decode($codes[$i]), $geshi->parse_code(), $c_content);
        }
        // >> end


        /*==========================================
        //                BUILD OUTPUT
        ==========================================*/

        $output .= $start_container . $start_content .$c_content . $s. $end_container . $end_container;
    }
    // end foreach

    return $output;
}

// caching = false;
$smarty->register_function('list_comments', 'smarty_list_comments', false);

?> 

 

// the getContentFromTags function

/**
*
* get text from tags
*
* @return string
*/
function getContentFromTags($string)
{
    preg_match_all('~<code>(.*?)</code>~s',$string, $matches);
    return $matches[0];
}

 

 

// A comment sample:

<p>a sample comment with code</p> <<--- TEXT
   <code>
<script type="text-javascript"> <<--- CODE BLOCK
       alert('hi');
</script>
</code>   <p>a line of text</p>   <code>
<script type="text-javascript">
       alert('alert');
</script>
</code> 

 

 

I've attached a screenshot below (it's still a work in progress, but you'll get the idea)

 

[attachment deleted by admin]

Link to comment
Share on other sites

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.