Jump to content

Archived

This topic is now archived and is closed to further replies.

Chelsove

Splitting text into teaser and main part

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?

Share this post


Link to post
Share on other sites
this may help a bit...

http://www.nstoia.com/toh/technical/teasers/index.php

Lite...

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
maybe[code]
<?php
$p = array('.', '!', '?');
$max = 350;
$x = min($max, strlen($content));
while (!in_array($content[--$x], $p) and $x >= 0);
if ($x >= 0) $out=substr($content, 0, $x+1);
else $out = 'Err'; // error
echo $out;
?>
[/code]

Share this post


Link to post
Share on other sites

×

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.