View Single Post
Old 10-28-2007, 07:07 PM   #6 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Here's something which might be useful, please don't just use the code as-is but take it's ideas and concepts (and main function hehe) to fit into your project. The code provided will (should) work in a standalone manner just to show you everything. It uses preg_split, I'm sure there are other alternatives of which this is just one example.

PHP Code:
<?php

/**
 * Splits a document by <h5>...</h5> elements
 *
 * This function does all of the work for you, hopefully.
 * Simply feed it an article and it will spit out 
 * the pages in an array containing title and body items.
 */
function split_pages($szArticle$szTag 'h5')
{
    
$aPages    = array();
    
$szTag     preg_quote($szTag);
    
$szPattern '#^\s*<' $szTag '>(.*?)</' $szTag '>\s*#im';
    
$aItems    preg_split($szPattern$szArticle, -1PREG_SPLIT_DELIM_CAPTURE);
    
array_shift($aItems);
    
    
// Loop through and sort into title/body groups
    
for ($i 0$l count($aItems); $i $l$i $i+2)
    {
        if (!isset(
$aItems[$i+1]))
            continue;
            
        
$aPages[] = array('title' => trim($aItems[$i]),
                          
'body'  => trim($aItems[$i+1]));
    }
    
    return 
$aPages;
}

// Here is our article to use 
$szArticle '<h5>Title for Page 1</h5>
Page one content

<h5>Title for Page 2</h5>
Page two content

<h5>Title for Page 3</h5>
Page three content'
;

// Gather the necessary variables together
$aPages split_pages($szArticle);
$iPage  = (isset($_GET['page']) && array_key_exists(intval($_GET['page']) - 1array_keys($aPages))) ? $_GET['page'] : 1;
$aPage  $aPages[$iPage 1];


/*
    Now onto some examples of how you might 
    like to use the pages array.
*/

?>

<!-- Show us what the $aPages array looks like -->
<pre><?php print_r($aPages?></pre>
<hr>

<!-- Show Current Page -->
<h2>Page <?php echo $iPage ?><?php echo $aPage['title'?></h2>
<p><?php echo nl2br($aPage['body']) ?></p>
<hr>

<!-- Pagination, Navigation, whatever you want to call it -->
<ol>
<?php foreach ($aPages as $t_iPage => $t_aPage) : $t_iPage++; ?>
    <li>
        <a href="?page=<?php echo $t_iPage ?>">
            Page <?php echo $t_iPage ?><?php echo $t_aPage['title'?>
        </a>
    </li>
<?php endforeach; ?>
</ol>
Salathe is offline  
Reply With Quote