Jump to content

Splitting text into teaser and main part


Chelsove

Recommended Posts

Hi,

I've got a problem with strings. We've got a lot of articles/stories stored in a database, but now I need to separate the text into two parts, that's going to be stored in different fields in the database (this is just how the content management system works). The first part is supposed to be fairly short, as it's just a teaser, and the rest of the text I'd put in the other field.

I was thinking that if say, the initial text could be max 350 characters long or 60-70 words, then I could search backwards from there until I hit some punctuation like ".", "?" or "!".

But I've had no luck finding any kind of functions on php.net that seems to suit me. I'm not an experienced php coder either, so I don't know my way around that well.

Anyone who can help?
Link to comment
https://forums.phpfreaks.com/topic/18041-splitting-text-into-teaser-and-main-part/
Share on other sites

First store the whole content in a variable, I'll call it $content. Then get the first 350 characters like this:

[code=php:0]
for ($x = 0; $x < 350; $x++) {
    $content_teaser .= $content[$x];
}
[/code]

Then to find the position of the last puncutation mark, use a for loop starting at the end and going backwards until it finds a puncuatation mark.

[code=php:0]
for ($x = len($content_teaser); $content_teaser[$x] != "." || $content_teaser[$x] != "!" || $content_teaser[$x] != "?"; $x--) {
    $punctuationmark = $x;
}
[/code]

Then finally, get all the characters up to that puncuation mark!

[code=php:0]
for ($x = 0; $x <= $puncuationmark; $x++) {
    $content_teaser .= $content[$x];
}
[/code]
Instead of transferring all the chars then counting backwards from the end check for the punctuation in first loop.

[code]<?php
for ($x = 0; $x < 350; $x++) {
    $content_teaser .= $content{$x};
    if ($content{$x} == '.' || $content{$x} == '?' || $content{$x} == '!') {
        $punc = $x+1;
    }
}
$content_teaser = substr($content,0,$punc);
?>[/code]

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.