Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap --  Выполняет перенос строки на данное количество символов с использованием символа разрыва строки.

Описание

string wordwrap ( string str [, int width [, string break [, boolean cut]]] )

Возвращает строку str с переносом в столбце с номером, заданном аргументом width. Строка разбивется с помощью аргумента break.

Аргументы width и break необязательны и по умолчанию равны 75 и '\n' соответственно.

Если аргумент cut установлен в 1, разрыв делается точно в заданной колонке. Поэтому если исходная строка содержит слово длиннее, чем заданная длина, то в этом случае слово будет разорвано. (См. второй пример).

Замечание: Необязательный аргумент cut был добавлен в PHP 4.0.3

Пример 1. Пример использования wordwrap()

<?php
$text
= "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo
"$newtext";
?>

Этот пример выведет:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Пример 2. Пример использования wordwrap()

<?php
$text
= "Очень длинное слоооооооооооооооово.";
$newtext = wordwrap($text, 8, "\n", 1);

echo
"$newtext\n";
?>

Этот пример выведет:

Очень
длинное
слоооооо
оооооооо
оово.

См. также описание функций nl2br() и chunk_split().



SWF> <vsprintf
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
wordwrap
buganini at gmail dot com
30-Oct-2007 02:33
function strwidth($s){
/*
put some fix for ambiguous width hese
*/
                $ret = mb_strwidth($s, 'UTF-8');
                return $ret;
        }

        function mb_wordwrap($str, $wid, $tag){
                $pos = 0;
                $tok = array();
                $l = mb_strlen($str, 'UTF-8');
                if($l == 0){
                        return '';
                }
                $flag = false;
                $tok[0] = mb_substr($str, 0, 1, 'UTF-8');
                for($i = 1 ; $i < $l ; ++$i){
                        $c = mb_substr($str, $i, 1, 'UTF-8');
                        if(!preg_match('/[a-z\'\"]/i',$c)){
                                ++$pos;
                                $flag = true;
                        }elseif($flag){
                                ++$pos;
                                $flag = false;
                        }
                        $tok[$pos] .= $c;
                }

                $linewidth = 0;
                $pos = 0;
                $ret = array();
                $l = count($tok);
                for($i = 0 ; $i < $l ; ++$i){
                        if($linewidth + ($w = strwidth($tok[$i])) > $wid){
                                ++$pos;
                                $linewidth = 0;
                        }
                        $ret[$pos] .= $tok[$i];
                        $linewidth += $w;
                }
                return implode($tag, $ret);
        }
andrej dot pavlovic at gmail dot com
25-Oct-2007 10:12
Disregard my note from below, since the function only works for utf8 strings that can be encoded into ISO-8859-1.
andrej dot pavlovic at gmail dot com
25-Oct-2007 08:36
Wordwrap for utf8. Easy to understand and works with the $cut parameter:

<?php

function utf8_wordwrap($str,$width=75,$break="\n", $cut=false){
    return
utf8_encode(wordwrap(utf8_decode($str), $width, $break, $cut));
}

?>
golanzakaiATpatternDOTcoDOTil
07-Oct-2007 10:39
/**
     * Wordwrap without unnecessary word splitting using multibyte string functions
     *
     * @param string $str
     * @param int $width
     * @param string $break
     * @return string
     * @author Golan Zakai <golanzakaiATpatternDOTcoDOTil>
     */
    function _wordwrap( $str, $width, $break ) {
        $formatted = '';
        $position = -1;
        $prev_position = 0;
        $last_line = -1;
       
        /// looping the string stop at each space
        while( $position = mb_stripos( $str, " ", ++$position, 'utf-8' ) ) {
            if( $position > $last_line + $width + 1 ) {
                $formatted.= mb_substr( $str, $last_line + 1, $prev_position - $last_line - 1, 'utf-8' ).$break;
                $last_line = $prev_position;
            }
            $prev_position = $position;
        }
       
        /// adding last line without the break
        $formatted.= mb_substr( $str, $last_line + 1, mb_strlen( $str ), 'utf-8' );
        return $formatted;
    }
me at NOJUNKPLEASE dot callum-macdonald dot com
24-Sep-2007 08:52
luismorrison's function will split a string into a first and second line *only*. If your string is 100 characters long and you wrap at 30 characters you will end up with 30 chars on line 1 and 70 on line 2.

I've included an English translation here for reference as I was going round the bend trying to figure it out in Spanish! :)

<?php
   
function splitstroverflow($chain,$length) {
       
$pri_line = array();
       
$seg_line = array();
       
$words = explode(" ",trim($chain));
      
        for (
$i = 0; $i < count($words); $i++) {
           
$sum += strlen($words[$i])+1;
            if (
$sum >= $length) $seg_line[] = $words[$i] . " ";
            else
$pri_line[] = $words[$i] . " ";
        }
      
        for (
$i = 0; $i < count($pri_line); $i++)
           
$lines[0] .= $pri_line[$i];
          
        for (
$i = 0; $i < count($seg_line); $i++)
           
$lines[1] .= $seg_line[$i];
      
        return
$lines;
    }
?>
luismorrison at gmail dot com
16-Aug-2007 10:21
i wrote this by mistake because i didn't know that the same function already exists in PHP.. well shit happens, its quite simple but maybe this will help you someday in your project. The difference is that the one i wrote, called 'splitstroverflow()', cuts given string and parses into arrays to do whatever you like with them.

<?php
   
function splitstroverflow($cadena,$longitud) {
       
$pri_renglon = array();
       
$seg_renglon = array();
       
$palabras = explode(" ",trim($cadena));
       
        for (
$i = 0; $i < count($palabras); $i++) {
           
$sum += strlen($palabras[$i])+1;
            if (
$sum >= $longitud) $seg_renglon[] = $palabras[$i] . " ";
            else
$pri_renglon[] = $palabras[$i] . " ";
        }
       
        for (
$i = 0; $i < count($pri_renglon); $i++)
           
$renglones[0] .= $pri_renglon[$i];
           
        for (
$i = 0; $i < count($seg_renglon); $i++)
           
$renglones[1] .= $seg_renglon[$i];
       
        return
$renglones;
    }
?>

Usage:
<?php
    splitstroverflow
(str longString,int lenght);
   
$myrow = splitstroverflow("This is my long long long string",18);

   
// the array counts 2 elements
    // Array
    // (
    //     [0] => "This is my long"
    //     [1] => "long long string"
    // )
?>
fatchris
29-Jun-2007 02:11
If your string has some html entities, then it might split one in half. e.g.

<?php
/*
Outputs (Renders):

Pr
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571