For people who want to use the double quote to group words/fields, kind of like CSV does, you can use the following expression:
<?php
$keywords = preg_split( "/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", "textline with, commas and \"quoted text\" inserted", 0, PREG_SPLIT_DELIM_CAPTURE );
?>
Which will result in:
Array
(
[0] => textline
[1] => with
[2] => commas
[3] => and
[4] => quoted text
[5] => inserted
)
preg_split
(PHP 4, PHP 5)
preg_split — Separar una cadena por una expresión regular
Descripción
Separa la cadena dada mediante una expresión regular.
Lista de parámetros
- patron
-
El patrón a buscar, como una cadena.
- asunto
-
La cadena de entrada.
- limite
-
Si se especifica, entonces sólo se devuelve una cantidad de hasta limite sub-cadenas, y si limite es -1, quiere decir "sin límite", lo cual es útil cuando se quiere pasar un valor al parámetro banderas .
- banderas
-
banderas puede ser cualquier combinación de las siguientes banderas (combinadas con el operador de bits |):
- PREG_SPLIT_NO_EMPTY
- Si esta bandera es definida, preg_split() sólo devolverá segmentos no-vacíos.
- PREG_SPLIT_DELIM_CAPTURE
- Si se define esta bandera, las expresiones entre paréntesis en el patrón de delimitación serán capturadas y devueltas también.
- PREG_SPLIT_OFFSET_CAPTURE
-
Si se define esta bandera, para cada coincidencia encontrada, se devolverá también la posición de la cadena anexa. Note que esto modifica el valor de retorno a una matriz en donde cada elemento es una matriz consistente de la cadena coincidente en la posición 0 y su desplazamiento de cadena al interior de asunto en la posición 1.
Valores retornados
Devuelve una matriz que contiene sub-cadenas de asunto , separadas sobre ciertos límites coincidentes con patron .
Registro de cambios
| Versión | Descripción |
|---|---|
| 4.3.0 | Se agregó PREG_SPLIT_OFFSET_CAPTURE |
| 4.0.5 | Se agregó PREG_SPLIT_DELIM_CAPTURE |
| 4.0.0 | El parámetro banderas fue agregado |
Ejemplos
Example #1 Ejemplo de preg_split(): Obtener las partes de una cadena de búsqueda
<?php
// separar la frase por cualquier numero de comas o caracteres de espacio,
// incluyendo " ", \r, \t, \n y \f
$palabras_clave = preg_split("/[\s,]+/", "lenguaje hipertexto, programación");
?>
Example #2 Separar una cadena en sus caracteres
<?php
$cadena = 'cadena';
$caracteres = preg_split('//', $cadena, -1, PREG_SPLIT_NO_EMPTY);
print_r($caracteres);
?>
Example #3 Separar una cadena en coincidencias y sus desplazamientos
<?php
$cadena = 'programación lenguaje hipertexto';
$caracteres = preg_split('/ /', $cadena, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($caracteres);
?>
El resultado del ejemplo seria:
Array ( [0] => Array ( [0] => programación [1] => 0 ) [1] => Array ( [0] => lenguaje [1] => 13 ) [2] => Array ( [0] => hipertexto [1] => 22 ) )
Notes
Si no necesita el poder de las expresiones regulares, es posible usar alternativas más rápidas (aunque más simples) como explode() o str_split().
preg_split
29-May-2008 12:56
27-May-2008 04:08
When I try to get \n delimited lines to an array from a file, preg_split gives one more array element which contains null string. Assume file contains
line1
line2
$lines = preg_split("/\n/", fread($fh, filesize($filename)));
$lines{
[0] => line1
[1] => line2
[2] =>
}
Same problem exists for explode as weel.
(this might be a feature of "PHP", not a problem.)
04-Sep-2007 10:29
I was having trouble getting the PREG_SPLIT_DELIM_CAPTURE flag to work because I missed reading the "parenthesized expression" in the documentation :-(
So the pattern should look like:
/(A)/
not just
/A/
and it works as described/expected.
14-Nov-2006 02:56
[Editor's Note: You can use php's wordwrap() to do the exact same thing]
This script splits a text into portions of a defined max. size, which will never be exceeded, and doesnt cut words. (Per portion it adds as many words as possible without exceeding the char-limit)
the only exception where a portion would be bigger than the limit, is when there's a word thats longer than the max_size, but you could quite easily change the script so it regards this.
<?
$str= 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
$max_size = 50;
$words = preg_split("/[\040]+/", $str, -1);
$r=0;
for($i=0; $i < count($words); $i++) {
if (strlen($line[$r] . $words[$i] . ' ') < $max_size) $line[$r] .= $words[$i] . ' ';
else
{
$r++;
$line[$r] .= $words[$i] . ' ';
}
}
print_r ($line);
?>
Result:
Array
(
[0] => Lorem ipsum dolor sit amet, consectetur
[1] => adipisicing elit, sed do eiusmod tempor
[2] => incididunt ut labore et dolore magna aliqua. Ut
[3] => enim ad minim veniam, quis nostrud exercitation
[4] => ullamco laboris nisi ut aliquip ex ea commodo
[5] => consequat. Duis aute irure dolor in
[6] => reprehenderit in voluptate velit esse cillum
[7] => dolore eu fugiat nulla pariatur. Excepteur sint
[8] => occaecat cupidatat non proident, sunt in culpa
[9] => qui officia deserunt mollit anim id est laborum.
)
04-Dec-2005 02:53
Be advised
$arr = preg_split("/x/", "x" );
print_r($arr);
will output:
Array
(
[0] =>
[1] =>
)
That is it will catch the 2 empty string on each side of the delimiter.
23-Mar-2005 05:41
preg_split() behaves differently from perl's split() if the string ends with a delimiter. This perl snippet will print 5:
my @a = split(/ /, "a b c d e ");
print scalar @a;
The corresponding php code prints 6:
print count(preg_split("/ /", "a b c d e "));
This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl's split()) but it might surprise perl programmers.
25-Sep-2004 05:01
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,
$preg_split('(/ /)', '1 2 3 4 5 6 7 8', 4 ,PREG_SPLIT_DELIM_CAPTURE );
returns
('1', ' ', '2', ' ' , '3', ' ', '4 5 6 7 8')
So you actually get 7 array items not 4
29-May-2002 09:01
The above description for PREG_SPLIT_OFFSET_CAPTURE may be a bit confusing.
When the flag is or'd into the 'flags' parameter of preg_split, each match is returned in the form of a two-element array. For each of the two-element arrays, the first element is the matched string, while the second is the match's zero-based offset in the input string.
For example, if you called preg_split like this:
preg_split('/foo/', 'matchfoomatch', -1, PREG_SPLIT_OFFSET_CAPTURE);
it would return an array of the form:
Array(
[0] => Array([0] => "match", [1] => 0),
[1] => Array([1] => "match", [1] => 8)
)
Note that or'ing in PREG_DELIM_CAPTURE along with PREG_SPLIT_OFFSET_CAPTURE works as well.
