Registreren

    Informatie

    Het is heel gemakkelijk om lid te worden. Door je gegevens op te geven op de registratie pagina ontvang je automatisch een email met je inlog gegevens.

  • Registreer je hier

Aanmelden

    Informatie

    Omdat je niet aangemeld bent is het gebruikerspaneel niet beschikbaar. Vul hiernaast je gegevens in om gebruik te maken van het gebruikerspaneel.

Aanmeldformulier


substr_sentences() en substr_words()

PHP is een scripttaal, die bedoeld is om op webservers dynamische webpagina's te creëren. PHP is in 1994 ontworpen door Rasmus Lerdorf, een senior software engineer bij IBM. Destijds was de taal duidelijk geïnspireerd door Perl.

Aanvankelijk stonden de letters PHP voor Personal Home Page (de volledige naam was Personal Home Page/Forms Interpreter, PHP/FI). Sinds PHP 3.0 is de betekenis een recursief acroniem geworden: PHP: Hypertext Preprocessor.

substr_sentences() en substr_words()

Berichtdoor Zunflappie » 07 Nov 2011 13:49

De functie substr() kan een string afkorten.
Handig als je een soort van 'inleiding' van een artikel wilt weergeven, maar hiervoor geen apart opgeslagen inleiding hebt. Je geeft gewoon een klein stukje van het hele artikel weer.

Voorbeeld
Jip en Janneke vertoeven op straat. Ze zijn alleen. Maar zijn ze echt alleen? Nee! Gelukkig loopt Poes er ook, net zoals Mies. En Aap? Aap is er niet bij!


substr($string, 0, 20): Jip en Janneke verto
substr_words($string, 0, 10): Jip en Janneke vertoeven op straat. Ze zijn alleen. Maar
substr_sentences($string, 0, 3): Jip en Janneke vertoeven op straat. Ze zijn alleen. Maar zijn ze echt alleen?
substr_sentences($string, 0, 3, 50): Jip en Janneke vertoeven op straat.

substr_sentences()
PHP
Code: Alles selecteren
<?php

function substr_sentence($string$start=0$limit=10$max_char 300)
    {
    
/* This functions cuts a long string in sentences.
    *
    * substr_sentence($string, $start, $limit);
    * $string = 'A example. By someone that loves PHP. Do you? We do!';
    * $start = 0; // we would start at the beginning
    * $limit = 10; // so, we get 10 sentences (not 10 words or characters!)
    *
    * It's not as substr()) in single characters.
    * It's not as substr_words() in single words.
    * 
    * No more broken lines in a story. The story/article must go on!
    *
    * Written by Eddy Erkelens "Zunflappie"
    * Published on www.mastercode.nl 
    * May be free used and adapted
    *
    */
    
    // list of sentences-ends. All sentences ends with one of these. For PHP, add the ;
    
$end_characters = array(
                
'.'
                
'?',
                
'!'
                
);
    
    
// put $string in array $parts, necessary evil
    
$parts = array($string);            
        
    
// foreach interpunctation-mark we will do this loop
    
foreach($end_characters as $end_character)
        {
        
// go thru each part of the sentences we already have
        
foreach($parts as $part)
            {
            
// make array with the new sentences
            
$sentences[] = explode($end_character$part);
            }
        
        
// unfortunately explode() removes the end character itself. So, place it back
        
foreach($sentences as $sentence)
            {
            
// some strange stuff
            
foreach($sentence as $real_sentence)
                {
                
// empty sentence we do not want
                
if($real_sentence != '')
                    {
                    
// if there is already an end-character, dont place another one
                    
if(in_array(substr($real_sentence, -11), $end_characters))
                        {
                        
// store for next round
                        
$next[] = trim($real_sentence);        
                        }
                    else
                        {
                        
// store for next round
                        
$next[] = trim($real_sentence).$end_character;    
                        }
                    }
                }
            }
            
        
// store for next round
        
$parts $next;
        
        
// unset the remaining and useless stuff
        
unset($sentences$sentence$next);
        }    

    
// check for max-char-length
    
$total_chars 0;
    
$sentence_nr 0;
    
$sentences = array();
    
    
// walk thru each member of $part
    
foreach($parts as $part)
        {
        
// count the string-lenght and add this to $total_chars
        
$total_chars += strlen($part);
        
        
// if $total-chars is higher then max-char, dont add this sentences!
        
if($total_chars $max_char)
            {
            
$sentences[] = $part;
            }
        }

    
// return the shortened story as a string
    
return implode(" "array_slice($sentences$start$limit));
    }
?>


Zoals je ziet is substr() niet mooi.
substr_words() gaat nog, maar valt ook raar weg na het woordje Maar.
substr_sentences() doet het wel goed.
De laatste (optionele) parameter geeft een maximum aan karakters aan.
Zodra de zinnen meer karakters hebben dan het opgegeven aantal, zullen er minder zinnen teruggegeven worden. De zinnen blijven intact en er komen geen halve zinnen bij.

Voor de volledigheid krijg je ook de versie van substr_words() nog even.
Dit kan ook handig zijn, aangezien deze iets accurater (qua lengte) is dan substr_sentences().

substr_words()
PHP
Code: Alles selecteren
<?php

function substr_words
($string, $start=0, $limit=100, $link='')
    {
    /* This functions cuts a long string in words.
    *
    * substr_words($string, $start, $limit);
    * $string = 'A example. By someone that loves PHP. Do you? We do!';
    * $start = 0; // we would start at the beginning
    * $limit = 10; // so, we get 10 sentences (not 10 words or characters!)
    *
    * It's not as substr()) in single characters.
    *
    * Written by Eddy Erkelens "Zunflappie"
    * Published on www.mastercode.nl 
    * May be free used and adapted
    *
    */
        
    
// make a $return variable
    $return = '';
    
    
// check for " ", if there is, there is more then one word
    if(stripos($string," "))
        {
        // chop the string is pieces, word by word (inclusive readingmarks)
        $ex_str = explode(" ",$string);
        
        
// if there are more words then the $limit
        if(count($ex_str)>$limit)
            {
            // glue the $limit-words to eachother with a space
            for($i=0;$i<$limit;$i++)
                {
                $return.=$ex_str[$i]." ";
                }
            
            
// if given a 'read-more'-link, add this
            if($link != '')
                {
                // return the shortened string, with a read-more-link
                return $return . '...<br><a class="readmore" href="'.$link.'">&raquo; read more</a>';    
                
}
            else
                
{
                // return the shortened string
                return $return;
                }
            }
        // not more words then limit
        else
            
{
            // return the orginal string
            return $string;
            }
        }
    // only one word
    else
        
{
        // return this one word
        return $string;
        }
    }

?>
Laatst gewijzigd door Zunflappie op 08 Nov 2011 13:54, in totaal 2 keer gewijzigd.
'K Ben er weer!
Gebruikers-avatar
Zunflappie
Teamlid
 
Berichten: 48
Geregistreerd: 06 Mrt 2006 12:48

Re: substr_sentences() en substr_words()

Berichtdoor emaas » 08 Nov 2011 11:45

Misschien is het handig om ook een maximaal limiet aan chars toe te voegen.
Hiermee kun je zeggen:
Geef de maximaal 3 regels of #chars (welke het eerste voorkomt).
emaas
 
Berichten: 8
Geregistreerd: 03 Nov 2011 13:22

Re: substr_sentences() en substr_words()

Berichtdoor Zunflappie » 08 Nov 2011 13:43

Is inderdaad wel een optie, met een 'nadeel' dat je dan van de syntax van substr() afwijkt.

[edit]
Is toegevoegd. Prima toevoeging, vooral bij langere zinnen!
'K Ben er weer!
Gebruikers-avatar
Zunflappie
Teamlid
 
Berichten: 48
Geregistreerd: 06 Mrt 2006 12:48


Terug naar PHP



Wie is er online?

Gebruikers in dit forum: Geen geregistreerde gebruikers en 1 gast


cron