2012-06-29 11 views
14

estoy buscando algo a lo largo de la línea dePHP: dividir una cadena larga sin palabras rompiendo

str_split_whole_word($longString, x) 

donde $longString es una colección de oraciones, y x es la longitud de caracteres para cada línea. Puede ser bastante largo, y básicamente quiero dividirlo en varias líneas en forma de matriz.

Así, por ejemplo,

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.'; 
$lines = str_split_whole_word($longString, x); 

$lines = Array(
    [0] = 'I like apple. You' 
    [1] = 'like oranges. We' 
    [2] = and so on... 
) 

Respuesta

12

Esta solución garantiza que las líneas se crean sin palabras que se rompen, lo que no se va a utilizar ajuste de línea(). Utilizará el espacio para explotar la cadena y luego usar un foreach para recorrer la matriz y crear las líneas sin romper las obras y con una longitud máxima que se define usando $maxLineLength. A continuación está el código, hice algunas pruebas y funciona bien.

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.'; 

$arrayWords = explode(' ', $longString); 

$maxLineLength = 18; 

$currentLength = 0; 
$index = 0; 

foreach ($arrayWords as $word) { 
    // +1 because the word will receive back the space in the end that it loses in explode() 
    $wordLength = strlen($word) + 1; 

    if (($currentLength + $wordLength) <= $maxLineLength) { 
     $arrayOutput[$index] .= $word . ' '; 

     $currentLength += $wordLength; 
    } else { 
     $index += 1; 

     $currentLength = $wordLength; 

     $arrayOutput[$index] = $word; 
    } 
} 
+2

Marcio, gracias por tu ayuda. ¡Esto ayuda justo como lo describió! – musicliftsme

+0

@ user796837, ¡No importa, me alegra ayudarte! –

38

La solución más sencilla es utilizar wordwrap(), y explode() en la nueva línea, así:

$array = explode("\n", wordwrap($str, $x)); 

Dónde $x es una serie de caracteres para envolver el cuerda puesta

+10

Esto es tan simple y memorable; debería ser la respuesta aceptada! –

+2

Esto funcionaría muy bien si aún no tiene saltos de línea en la cadena. – BakerStreetSystems

7

Uso wordwrap() para insertar los saltos de línea, a continuación, explode() en esos saltos de línea:

// Wrap at 15 characters 
$x = 15; 
$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.'; 
$lines = explode("\n", wordwrap($longString, $x)); 

var_dump($lines); 
array(6) { 
    [0]=> 
    string(13) "I like apple." 
    [1]=> 
    string(8) "You like" 
    [2]=> 
    string(11) "oranges. We" 
    [3]=> 
    string(13) "like fruit. I" 
    [4]=> 
    string(10) "like meat," 
    [5]=> 
    string(5) "also." 
} 
+0

Exactamente lo que quiero :) ¡Gracias! – Harsha

1

función Hecho de Marcio Simao comentario

function explodeByStringLength($string,$maxLineLength) 
{ 
    if(!empty($string)) 
    { 
     $arrayWords = explode(" ",$string); 

     if(count($arrayWords) > 1) 
     { 
      $maxLineLength; 
      $currentLength = 0; 

      foreach($arrayWords as $word) 
      { 
       $wordLength = strlen($word); 
       if(($currentLength + $wordLength) <= $maxLineLength) 
       { 
        $currentLength += $wordLength; 
        $arrayOutput[] = $word; 
       } 
       else 
       { 
        break; 
       } 
      } 

      return implode(" ",$arrayOutput); 
     } 
     else 
     { 
      return $string; 
     }  
    } 
    else return $string; 
} 
1

Pruebe esta función .......

<?php 
/** 
* trims text to a space then adds ellipses if desired 
* @param string $input text to trim 
* @param int $length in characters to trim to 
* @param bool $ellipses if ellipses (...) are to be added 
* @param bool $strip_html if html tags are to be stripped 
* @param bool $strip_style if css style are to be stripped 
* @return string 
*/ 
function trim_text($input, $length, $ellipses = true, $strip_tag = true,$strip_style = true) { 
    //strip tags, if desired 
    if ($strip_tag) { 
     $input = strip_tags($input); 
    } 

    //strip tags, if desired 
    if ($strip_style) { 
     $input = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$input); 
    } 

    if($length=='full') 
    { 

     $trimmed_text=$input; 

    } 
    else 
    { 
     //no need to trim, already shorter than trim length 
     if (strlen($input) <= $length) { 
     return $input; 
     } 

     //find last space within length 
     $last_space = strrpos(substr($input, 0, $length), ' '); 
     $trimmed_text = substr($input, 0, $last_space); 

     //add ellipses (...) 
     if ($ellipses) { 
     $trimmed_text .= '...'; 
     }  
    } 

    return $trimmed_text; 
} 
?> 

Crédito: http://www.ebrueggeman.com/blog/abbreviate-text-without-cutting-words-in-half

+1

Al menos agregue crédito para eso: http://www.ebrueggeman.com/blog/abbreviate-text-without-cutting-words-in-half –

Cuestiones relacionadas