Jump to content

Recommended Posts

My website is going to host various and future pieces of my writing. Some of the pieces are going to be very long, so I need to split them up over multiple pages. I have an input form through which I can type or paste a piece of writing and have it inserted into MySQL. What I need now is to have PHP automatically insert page breaks before the piece is inserted.

 

I was told I could use regular expressions, or I could use PHP to traverse the string and insert a page break, say, after 1400 characters so long as it ends on a period.

 

I know of str_replace, but how do I set it go a certain amount of characters? This whole pagination thing has me completely stumped. I'm not looking to paginate display results. I'm displaying one result split up in pages.

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/66930-traverse-and-insert-page-breaks/
Share on other sites

You can do something like this:

$MAX_LEN = 300;
do
{
$pos = strpos($string, ".", $pos);
if ($pos >= $MAX_LEN)
	//cut!
}while ($pos !== false);

 

That will find the position of a period after a maximum length of characters that you specify. Do you need help with the "cut!" code?

Basically the only function u need for this is substr(). Consider the following example:

 

$string = 'this is my article......which has thousand of characters';
$string = substr($string, 0, 1400);
$dotPos = strrpos($string, '.');
$string = substr($string, 0, $dotPos+1);
echo $string;

 

The code will get the first 1400 characters, find the last occurrence of a dot and remove the following part, so it shows full sentences.

 

To make it with pagination then use something like:

$string = 'this is my article......which has thousand of characters';
$page = 2;
$nrChars = 1400;
$start = $page * $nrChars - $nrChars;
$end = $page * $nrChars;
$string = substr($string, $start, $end);
echo $string;

 

$page is manually set but it may be a get variable which is passed when someone clicks a link and makes the url: mypage.php?page=2. The start and end is calculated based on the actual page. Did not test it but it should work that way. Ill try to find a way to show full senteces both at the start and the end and if so ill post the code.

Many thanks for the replies. I'm having some trouble putting your code into context though. Is this before I insert the text into the database, or is it for displaying the text?

 

This is what I'm using to process my form, which consists of Title, Type (poetry, fiction, nonfiction), Text, and Year.

<?php
require("db/config.php");
require("db/opendb.php");

$id =  "";
$title = $_POST[title];

$type = $_POST[type];
    if ($type == "1") {
    $table = "poems";
    }

    if ($type == "2") {
    $table = "fiction";
    }

    if ($type == "3") {
    $table = "nonfiction";
    }

    $text = $_POST[text];
    $year = $_POST[year];

    $query = mysql_query("INSERT INTO $table(id, title, text, year) VALUES ('$id', '$title', '$text', '$year')") or     die (mysql_error());

require("db/closedb.php");
require("success.php");

?>

 

 

 

Then this is what I'm using to display it:

<?php
import_request_variables('G', 'url_');

if ((isset($_GET[piece])) && ($_GET[piece] != "")) {

require("db/config.php");
require("db/opendb.php");

    $query = "SELECT text, title, year FROM nonfiction WHERE id=". mysql_escape_string($_GET[piece]);
    $result = mysql_query($query);
    $content = mysql_fetch_assoc($result);

require("db/closedb.php");

    echo "<h3>$content[title]</h3><br />";
    echo nl2br("<p>$content[text]</p><br />");
    echo "<span class=\"textcopy\">© $content[year]</span> <span class=\"courier\">FridayRain</span>";
    } else {
    echo "<span class=\"choose\">Please choose a title.
        <br /><br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br /><br />
    </span>";
    }
?>

Actually the code i provided uses string manipulation, so u should first get the article from the db, then show part of it. The code isnt perfect as it shows full sentences only in the end of the article, not beginning, but if u can modify it further then it will fit your needs. It is also meant to have pages, ex:

 

$actualPage = $_GET['page'];
$article = 'long long article';
$maxPages = ceil(strlen($article) / 1400);
for($i=1; $<=$maxPages; $i++){
    if($actualPage == $i){
       echo "$i"; //if it is the current page dont show page number as link
    } else{
       echo "<a href="\index.php?page={$i}\">{$i}</a>;
    }
}

 

Hope it helps.

 

$actualPage = $_GET['page'];
$article = 'long long article';
$maxPages = ceil(strlen($article) / 1400);
for($i=1; $<=$maxPages; $i++){
    if($actualPage == $i){
       echo "$i"; //if it is the current page dont show page number as link
    } else{
       echo "<a href="\index.php?page={$i}\">{$i}</a>;
    }
}

 

Is that for statement correct? I'm getting a white screen error:

 

Parse error: syntax error, unexpected T_IS_SMALLER_OR_EQUAL, expecting T_VARIABLE or '$'

  • 2 weeks later...

Using some of this code, how could I use strrpos to search for the end of a paragraph?

 

Also, I got the code to cut the piece after so many characters, but how do I assign page numbers for the rest of the piece? Do I need a FOR LOOP maybe?

try

<?php
$a = file_get_contents('20740-8.txt');
//split $a per pages
$car_per_page = 10000;
$pages = array();
while (strlen($a) > 0){
$b = str_split($a, $car_per_page);
$x = $b[0];
unset($b[0]);
$a = implode($b);
$i = strlen($x);
if (strlen($a) > 0) {
	while ($x[--$i] != ' ');
	$y = substr($x, 0, $i);
	$a = substr($x, $i). $a;
} else {
	$y = $x;
}
$pages[] = $y;
}
echo 'Total pages: ', count($pages), '<br />';
$page = $_GET['page'] + 0;
echo ($page + 1).' page;<br />';
echo '<pre>', $pages[$page], '</pre>';
for($i = 0; $i < count($pages); $i++) {
if ($i != $page) echo ' <a href="?page='.$i.'">'.($i +1).'</a> '; else echo ' '. ($i+1).' ';
}
?>

I used your code virtually verbatim, but there's a small problem. The page number doesn't match the text of the page link. The link for Page 2 is set for page=3. It seems that it's counting up from 0 instead of 1.

 

And how do I make it end each page on a period, preferably after a whole paragraph?

in URL for 2nd page is 'page=1' if you want that this numbewr match change line

$pages = array();

to

$pages = array('');

 

and

echo 'Total pages: ', count($pages), '<br />';

to

echo 'Total pages: ', count($pages) - 1, '<br />';

 

and

$page = $_GET['page'] + 0;

to

$page = $_GET['page']  ? $_GET['page'] : 1;

 

and lines

for($i = 0; $i < count($pages); $i++) {

if ($i != $page) echo ' <a href="?page='.$i.'">'.($i +1).'</a> '; else echo ' '. ($i+1).' ';

}

to

for($i = 1; $i < count($pages); $i++) {

if ($i != $page) echo ' <a href="?page='.$i.'">'.($i).'</a> '; else echo ' '. $i.' ';

}

I'm getting an error because of the semi-colon.

 

Parse error: syntax error, unexpected ';'

 

 

Actually it's missing a closing ), but where do I put it? If I put it at the end with the other two, it's doesn't end on a period.

I tweaked it a bit and this is what I'm using:

 

while (!in_array($x[--$i], array(". ", "? ", "! ", "\n", "\r")));

 

I added the missing parenthesis and put a space after the period, question mark, and exclamation point. This seems to end pages at the end of a paragraph, but on the next page there's an extra space above where the text starts because I'm using the NL2BR command to display my text. How might I omit the space between paragraphs so it doesn't appear on subsequent pages?

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.