<?php
// Remove words if more than max allowed character are insert or add a string in case less than min are displayed
// Example: LimitText("The red dog ran out of thefence",15,20,"<br>");
function LimitText($Text,$Min,$Max,$MinAddChar) {
if (strlen($Text) < $Min) {
$Limit = $Min-strlen($Text);
$Text .= $MinAddChar;
}
elseif (strlen($Text) >= $Max) {
$words = explode(" ", $Text);
$check=1;
while (strlen($Text) >= $Max) {
$c=count($words)-$check;
$Text=substr($Text,0,(strlen($words[$c])+1)*(-1));
$check++;
}
}
return $Text;
}
?>
explode
(PHP 4, PHP 5)
explode — Divide una cadena por otra
Descripción
Devuelve una matriz de cadenas, cada una de las cuales es una subcadena de cadena formada mediante su división en las fronteras marcadas por la cadena separador . Si se especifica limite , la matriz devuelta contendrá un máximo de limite elementos con el último conteniendo el resto de la cadena .
Si separador es una cadena vacía (""), explode() devuelve un valor igual a FALSE. If separador contiene un valor que no está presente en cadena , la función explode() devuelve una matriz que contiene la cadena .
Si el parámetro limite es negativo, se devuelven todos los valores salvo el último limite . Este comportamiento se incluyó en la versión de PHP 5.1.0.
Aunque la función implode() por razones históricas puede aceptar sus parámetros en cualquier orden, no sucede lo mismo con la función explode(). Por tanto, se debe asegurar que el argumento separador se indique antes que el argumento cadena .
Note: El parámetro limite se incluyó en PHP 4.0.1.
Example #1 Ejemplos de explode()
<?php
// Ejemplo 1
$pizza = "trozo1 trozo2 trozo3 trozo4 trozo5 trozo6";
$trozos = explode(" ", $pizza);
echo $trozos[0]; // trozo1
echo $trozos[1]; // trozo2
// Ejemplo 2
$datos = "usuario:*:1023:1000::/home/usuario:/bin/sh";
list($usuario, $contrasena, $uid, $gid, $gecos, $home, $shell) = explode(":", $datos);
echo $usuario; // usuario
echo $contrasena; // *
?>
Example #2 Ejemplo del parámetro limite
<?php
$cadena = 'uno|dos|tres|cuatro';
// limite positivo
print_r(explode('|', $cadena, 2));
// limite negativo (desde PHP 5.1)
print_r(explode('|', $cadena, -1));
?>
El resultado del ejemplo seria:
Array ( [0] => uno [1] => dos|tres|cuatro ) Array ( [0] => uno [1] => dos [2] => tres )
Note: Esta función es segura binariamente.
See also preg_split(), spliti(), split(), strtok(), and implode().
explode
04-Dec-2008 09:02
16-Nov-2008 05:38
A really better and shorter way to get extension is via:
<?php $extension = end(explode('.', $filename)); ?>
this will print the last part after the last dot :)
29-Aug-2008 12:24
For anyone trying to get an array of key => value pairs from a query string, use parse_str. (Better alternative than the explode_assoc function listed way down the page unless you need different separators.)
15-Oct-2007 02:26
coroa at cosmo-genics dot com mentioned using preg_split() instead of explode() when you have multiple delimiters in your text and don't want your result array cluttered with empty elements. While that certainly works, it means you need to know your way around regular expressions... and, as it turns out, it is slower than its alternative. Specifically, you can cut execution time roughly in half if you use array_filter(explode(...)) instead.
Benchmarks (using 'too many spaces'):
Looped 100000 times:
preg_split: 1.61789011955 seconds
filter-explode: 0.916578054428 seconds
Looped 10000 times:
preg_split: 0.162719011307 seconds
filter-explode: 0.0918920040131 seconds
(The relation is, evidently, pretty linear.)
Note: Adding array_values() to the filter-explode combination, to avoid having those oft-feared 'holes' in your array, doesn't remove the benefit, either. (For scale - the '9' becomes a '11' in the benchmarks above.)
Also note: I haven't tested anything other than the example with spaces - since djogo_curl at yahoo's note seems to imply that explode() might get slow with longer delimiters, I expect this would be the case here, too.
I hope this helps someone. :)
09-Dec-2006 07:49
Note that explode, split, and functions like it, can accept more than a single character for the delimiter.
<?php
$string = "Something--next--something else--next--one more";
print_r(explode('--next--',$string));
?>
01-Dec-2004 04:50
Being a beginner in php but not so in Perl, I was used to split() instead of explode(). But as split() works with regexps it turned out to be much slower than explode(), when working with single characters.
16-Nov-2003 08:01
To split a string containing multiple seperators between elements rather use preg_split than explode:
preg_split ("/\s+/", "Here are to many spaces in between");
which gives you
array ("Here", "are", "to", "many", "spaces", "in", "between");
