Pomoc - Szukaj - U¿ytkownicy - Kalendarz
Pe³na wersja: [PHP] rozwi±zany -> obciêcie tekstu z bazy ale nie uciêcie w po³owie s³owa
Forum PHP.pl > Forum > Przedszkole
john_doe
Witam,

mam pole w bazie zawieraj±ce text. Text oczywi¶cie a ró¿n± d³ugo¶æ. Zrobi³em wy¶wietlanie wpisów i substring( text,0,100) i link czytaj dalej. Jednak wiadomo, ¿e taki sposób jest do luftu bo ucina wyrazy etc.
Jak zrobiæ aby zostawiæ pe³ny wyraz na koñcu?

pozdrawiam

EDIT:

w oparciu o google napisa³em helper w CI

  1. <?php
  2.  
  3. /**
  4.  * truncate_string
  5.  *
  6.  * function trims a text without breaking the word just in the middle
  7.  * The simple algorithm is as follows:
  8.  * - Is the string longer than our limit ( in this case 250 )
  9.  * - Truncate the string to our limit
  10.  * - If we ended up in the middle of a word
  11.  * - Trim out that broken word by finding the previous space
  12.  *
  13.  * @access public
  14.  * @param $str given string to trim
  15.  * @param $max_len max length to remain after trim
  16.  * @return $new_str trimed string
  17.  */
  18. if ( ! function_exists('truncate_string'))
  19. {
  20. function truncate_string($str, $max_len)
  21. {
  22. if ( strlen($str) <= $max_len )
  23. return $str;
  24.  
  25. $new_str = substr($str, 0, $max_len);
  26. if ( substr($new_str,-1,1) != ' ' ) $new_str = substr($new_str, 0, strrpos($new_str, " "));
  27.  
  28. return $new_str;
  29. }
  30. }
  31.  
  32. ?>
sada
  1. preg_match('/^(.){0,100}[\s|\n]/',$text,$match);


gdzie zmienna
  1. $tekst
zawiera tekst do przyciêcia

w zmiennej
  1. $match[0]
masz obciêty tekst do 100 znaków
To jest wersja lo-fi g³ównej zawarto¶ci. Aby zobaczyæ pe³n± wersjê z wiêksz± zawarto¶ci±, obrazkami i formatowaniem proszê kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.