시소당
explode
(PHP 3, PHP 4 , PHP 5)
explode -- 문자열을 주어진 문자열을 기준으로 분리합니다.
설명
array explode ( string separator, string string [, int limit])
separator 문자열을 경계로 나누어진 string의 부분 문자열로 이루어지는 배열을 반환합니다. limit를 지정하면 마지막 원소가 나머지 문자열 전체를 가지는 최대 limit개 원소의 배열을 반환합니다.
separator가 빈 문자열("")이면, explode()은 FALSE를 반환합니다. separator가 string에 존재하지 않으면, explode()는 string를 포함하는 배열을 반환합니다.
비록 implode()가 관습에 의해 인자의 순서를 뒤바뀌는 것을 허용하더라도, explode()는 그렇지 않습니다. 반드시 separator 인자가 string 인자 앞에 위치하도록 해야합니다.
참고: limit 인자는 PHP 4.0.1 에서 추가되었습니다.
예 1. explode() 예제
<?php
// 예제 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode (" ",
$pizza);
echo
$pieces[0]; // piece1
echo
$pieces[1]; // piece2
// 예제 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user,
$pass,
$uid,
$gid,
$gecos,
$home,
$shell) = explode(":",
$data);
echo
$user; // foo
echo
$pass; // *
?>
참고: preg_split(), spliti(), split(), implode().
add a note User Contributed Notes
explode
janklopper.at.gmail.dot.com
28-Jun-2005 09:06
This is a better (altough untested) version of the lastword function, is searches from the end back to the begin until it finds seperator, and thus only searches the smalest possible part of the string. very helpfull for large strings.
function lastword(
$string,
$seperator=" ") {//last word of a string
$count=strlen(
$string);
$count--;
for(
$i=
$count;
$i--;
$i==0){
if(
$string[
$i]==
$seperator){
$location=
$i-(
$i*2);
return substr(
$string,
$location);
}
}
return;
}
hardy at mapscene dot de
23-Jun-2005 09:33
here are some usefully simple functions to get word-parts of an given string... i remember to that functions by using arexx on amiga :)
function words(
$string,
$seperator=" ") {//amount of words in the string
$array = explode(
$seperator,
$string);
return count(
$array);
}
function word(
$string,
$number=1,
$seperator=" ") {//word num of string
if(
$number>0)
$number--;
$array = explode(
$seperator,
$string);
if(count(
$array)>=
$number)
return
$array[
$number];
return;
}
function lastword(
$string,
$seperator=" ") {//last word of an string
$array = explode(
$seperator,
$string);
$number = count(
$array);
if(
$number>0) {
$number--;
return
$array[
$number];
}
return;
}
contact_trieu at hotmail dot com
16-Jun-2005 02:27
Sorry, this is a change to the function I previously submitted to limit a sentence by chars. This accounts for spaces, whereas the previous one I submitted does not. Again, this function is a modified version of other function mentioned previously.
<?php
function charLimit(
$string,
$length = 25,
$ellipsis = "...")
{
$words = explode(' ',
$string);
$curindex = 0;
$wcount = 0;
foreach(
$words as
$value){
$wcount += strlen(
$value)+1;
if(
$wcount>
$length-strlen(
$ellipsis)){
break;
}
$curindex++;
}
return implode(' ', array_slice(
$words, 0,
$curindex)) .
$ellipsis;
}
?>
contact_trieu at hotmail dot com
16-Jun-2005 04:44
Here is a modified version of the function below. Rather than limit by number of words, this should limit by number of characters. The function will cut off the sentence to the preceding word taking into consideration the ending "ellipsis".
function charLimit(
$string,
$length = 25,
$ellipsis = "...")
{
$words = explode(' ',
$string);
$curindex = 0;
$wcount = 0;
foreach(
$words as
$value){
$wcount += strlen(
$value);
if(
$wcount>
$length-strlen(
$ellipsis)){
break;
}
$curindex++;
}
return implode(' ', array_slice(
$words, 0,
$curindex)) .
$ellipsis;
}
m_b
01-Jun-2005 09:29
Here's how to split a text file into lines using explode(). This could be very useful for restoring backed up databases, when you need to pass every line (SQL statement) to MYSQL separatly:
$theFile = file_get_contents('file.txt');
$lines = array();
$lines = explode("\n",
$theFile);
$lineCount = count(
$lines);
for (
$i = 0;
$i <
$lineCount;
$i++){
echo
$lines[
$i]."<hr>";
}//for
The text lines are split by a horizontal line so you can see the effect in the browser
andy at savagescape dot com
18-May-2005 12:15
Here's Urban Heroes' function written with the ternary operator an dan inline assignment to make it slimmer still:
function word_limit(
$string,
$length = 50,
$ellipsis = "...") {
return (count(
$words = explode(' ',
$string)) >
$length) ? implode(' ', array_slice(
$words, 0,
$length)) .
$ellipsis :
$string;
}
Mart
03-May-2005 05:07
The associative array parsing example by hhabermann at pc-kiel dot de seems flawed to me.
Given
<?php
$data = 'One:1:two:2:three:3';
?>
it should be parsed with
<?php
function &parse(&
$data)
{
$data = explode("\n",
$data);
$num = count(
$data);
if (
$num % 2 || !
$num) {
return false;
}
for (
$i = 0;
$i <
$num / 2;
$i++) {
$ret[
$data[
$i * 2]] =
$data[
$i * 2 + 1];
}
return
$ret;
}
$data =& parse(
$data);
print_r(
$data);
?>
The output is as expected:
Array ( [One] => 1 [two] => 2 [three] => 3 )
nsetzer at allspammustdie dot physics dot umd dot edu
25-Apr-2005 09:57
Yet another "csv explode". It requires the nearest_neighbor function to work and that's handy in other situations as well. The code has the advantage (or disadvantage) of using strpos so that the PHP code doesn't transparently go through every character of the string. With very little modification this code could be used to allow the user to submit alternate deliminators that act like a ' or ".
<?php
function nearest_neighbor(
$individualGPS,
$world,
$races)
{
// find the nearest neighbor of each race
foreach (
$races as
$ethnicGroup)
$nearest[
$ethnicGroup] = strpos(
$world,
$ethnicGroup,
$individualGPS + 1);
// sort the nearest in ascending order
asort(
$nearest, SORT_NUMERIC);
reset(
$nearest);
// get the first non-false
foreach(
$nearest as
$neighborRace =>
$neighborLocale)
if (
$neighborLocale !== FALSE)
return array( 'char' =>
$neighborRace,
'str_loc' =>
$neighborLocale );
// went through all races and none are nearby
return FALSE;
}
function csv_explode(
$explodeOn,
$target)
{
// return FALSE if null string is the separator
if ( empty(
$explodeOn) )
return FALSE;
// set the search strings
$spotlightArr = Array(
$explodeOn, '"', "'");
$numExplosions = 0;
$explodedStrArr[0] =
$target;
$currentLocale = 0; // start at the beginning
// this loop doesn't have a conditional exit because it doesn't need one --
// either a nearest neighbor will be found, or it won't.
while (TRUE)
{
// get the next reserved character and its position
$nearest = nearest_neighbor(
$currentLocale,
$target,
$spotlightArr);
if (!
$nearest)
return
$explodedStrArr;
switch (TRUE)
{
// <<<<<<<<<<<<<<<<<<<< BEGIN CASE ' or " >>>>>>>>>>>>>>>>>>>>>>>>>>>
case (
$nearest['char'] == '\''):
case (
$nearest['char'] == '"'):
// in a string, find string end
$nextStrChar = strpos(
$target,
$nearest['char'],
$nearest['str_loc'] + 1);
if (
$nextStrChar === FALSE)
{
// no closing string until end of
$target so we're done
return
$explodedStrArr;
}
// change locale
$currentLocale =
$nextStrChar + 1;
break;
// <<<<<<<<<<<<<<<<<<<<<<< END CASE ' or " >>>>>>>>>>>>>>>>>>>>>>>>>> "
// <<<<<<<<<<<<<<<<<<< BEGIN CASE
$explodedON >>>>>>>>>>>>>>>>>>>>>>>
case (
$nearest['char'] ==
$explodeOn):
// found a mine (need to explode)
// record the stuff up to the end of the mine
$explodedStrArr[
$numExplosions] = substr(
$target,
$currentLocale,
$nearest['str_loc'] -
$currentLocale
);
// increment counter
$numExplosions++;
// change current locale
$currentLocale =
$nearest['str_loc'] + strlen(
$explodeOn);
break;
// <<<<<<<<<<<<<<<<<<<< END CASE
$explodedON >>>>>>>>>>>>>>>>>>>>>>>>
} // end switch
} // end while
}
?>
JUSTIN -AT- LUTHRESEARCH -DOT- COM
16-Apr-2005 09:02
A few changes to the proper case function above,
1.
$reval was not declared (So it was giving off a notice)
2. If the first word was not a alpha character, it would not capitalze the second, for example "I Like PHP (it's Cool)" should be: "I Like PHP (It's Cool)"
function properCase(
$strIn)
{
$retVal = null;
$arrTmp = explode(" ", trim(
$strIn));
for(
$i=0;
$i < count(
$arrTmp);
$i++)
{
$firstLetter = substr(
$arrTmp[
$i],0,1);
if(isAlpha(
$firstLetter)){
$rest = substr(
$arrTmp[
$i],1,strlen(
$arrTmp[
$i]));
$arrOut[
$i] = strtoupper(
$firstLetter).strtolower(
$rest);
}else{
$firstLetter = substr(
$arrTmp[
$i],0,1);
$SecondLetter = substr(
$arrTmp[
$i],1,1);
$rest = substr(
$arrTmp[
$i],2,strlen(
$arrTmp[
$i]));
$arrOut[
$i] =
$firstLetter . strtoupper(
$SecondLetter).strtolower(
$rest);
}
}
for(
$j=0;
$j < count(
$arrOut);
$j++)
$retVal .=
$arrOut[
$j]." ";
return trim(
$retVal);
}
function isAlpha(
$character) {
$c = Ord(
$character);
return (((
$c >= 64) && (
$c <= 90)) || ((
$c >= 97) && (
$c <= 122)));
}
Bob
12-Apr-2005 04:07
I only have access to a really old ver. of php so when I had to come up with a way to grab a filename w/o the suffix (.whatever) i came up with this:
function remSuffix (
$inputString) {
$origString =
$inputString;
$inputString = explode(".",strrev(
$inputString),2);
if (strlen(
$inputString[1])<>0) {
return strrev(
$inputString[1]);
} else
return
$origString;
}
takes string, if it has a '.', it returns everything in front of the last occurence of '.'
so :
echo remSuffix("some.file.txt");
will return
some.file
echo remSuffix("somefile.txt");
will return
somefile
if there is no '.' present, then the entire string is returned.
echo remSuffix("somefiletxt");
will return
somefiletxt
from the docs, it seems that in php5 that this can be accomplished by using a -ve limiter so use that instead of you have it!
richardkmiller at gmail dot com
12-Apr-2005 04:01
The function posted by tengel at fluid dot com didn't work for me -- it wouldn't compile. Here is the function I wrote to do the same thing. This function explodes a string, ignoring delimeters that appear inside double quotes. (Incidentally, it also removes double quotes from the exploded elements.)
This correctly parses, for example, a line from a CSV file like this:
10, "abc", "ACME, Inc.", 50.25
It's slow, but it works. (How could this be faster?)
function explode2(
$delimeter,
$string)
{
for (
$i = 0;
$i < strlen(
$string);
$i++)
{
if (
$string{
$i} == '"')
{
if (
$insidequotes)
$insidequotes = false;
else
$insidequotes = true;
}
elseif (
$string{
$i} ==
$delimeter)
{
if (
$insidequotes)
{
$currentelement .=
$string{
$i};
}
else
{
$returnarray[
$elementcount++] =
$currentelement;
$currentelement = '';
}
}
else
{
$currentelement .=
$string{
$i};
}
}
$returnarray[
$elementcount++] =
$currentelement;
return
$returnarray;
}
powerspike
15-Mar-2005 02:02
a very quick way to get a file extenstion would be -
$file_ext = array_pop(explode(".",
$real_filename));
array_pop will push the last element of the array in the assigned varable (ie
$file_ext) in this case.
emilyd at boreal (.) org
24-Feb-2005 06:20
Also, it seems any array element (at least using explode) is limited to 255 characters.
woltersware at ish dot de
29-Jan-2005 04:05
This is a simple way to get the ending of a file using explode
$str_filename = "maisfsd.fdfwadasc.eswfwefwe.rdyxfdasd.asda.sd.asd.JPG";
$dotarray = explode(".",
$str_filename);
$fileending =
$dotarray[(count(
$dotarray)-1)];
echo
$fileending;
Result: JPG
urbanheroes {at} gmail {dot} com
12-Jan-2005 08:08
The above function works well! Here's a slimmer version that works similarly:
<?php
function wordlimit(
$string,
$length = 50,
$ellipsis = "...")
{
$words = explode(' ',
$string);
if (count(
$words) >
$length)
return implode(' ', array_slice(
$words, 0,
$length)) .
$ellipsis;
else
return
$string;
}
?>
marcyboy45 at hotmail dot com
10-Jan-2005 10:04
I'm not going for the noble prize with this one, but it saves you having to writing something similar if the occasion ever presents itself! This is just a simple function to cut short a paragraph like what you'd see in the results of a web search. You can specify the number of words and the ellipsis which makes it quite flexible.
<?php
function wordlimit(
$string,
$length = 50,
$ellipsis = "...")
{
$paragraph = explode(" ",
$string);
if(
$length < count(
$paragraph))
{
for(
$i = 0;
$i <
$length;
$i++)
{
if(
$i <
$length - 1)
$output .=
$paragraph[
$i] . " ";
else
$output .=
$paragraph[
$i] .
$ellipsis;
}
return
$output;
}
return
$string;
}
?>
An example would look like:
<?php
$string = "This is a very simple function, but nifty nonetheless.";
print wordlimit(
$string, 5); // This is a very simple...
?>
mswitzer - propagandabydesign - com
15-Dec-2004 11:57
Just a clarification on matzie's comment. You only need double quotes if you want PHP to parse what is enclosed in them. A character (i.e. -, |, /) can be in single quotes, but anything php needs to parse (\n,\r,
$var) needs to be in double quotes.
The double quotes tell PHP to parse what is contained, single quotes tell PHP to spit it out as is without reacting to anything in it.
for instance:
<?php
$var = 'Hello'; ?>
The ouput of <?php echo '
$var'; ?> is
$var.
The ouput of <?php echo "
$var"; ?> is Hello.
djogo_curl at yahoo
01-Dec-2004 09: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.
matzie at dontspamme dot bitdifferent dot com
23-Nov-2004 07:59
The separator parameter in double quotes not single ones. Having got into the habit (for performance) of using double quotes only when I really want variable substitution etc, I was doing this (intending to split a string into lines)
<?PHP
$strFoo = "Hello
World
Goodbye
World";
$arrFoo = explode ('\n',
$strFoo);
?>
and it wasn't working. I changed the single quotes for double ones and it started working.
(Incidentally I then recombined the array back into a string implode()d with '\' (the Javascript line continuation character) to give a multi-line string that could be document.write()'d with Javascript).
corychristison }at{ lavacube (DOT) com
21-Nov-2004 04:06
Here is a small script I use to break a part search queries[example: "do-search"-"dont-search" ]
+ or no 'switch' is to add to search tearms
- for do not include in search
<?php
function parse_search (
$input) {
$c = count_chars(
$input, 0);
$c = (
$c[34]/ 2);
if(!strstr(
$c, ".") &&
$c != "0"){
$input = explode("\"",
$input);
$include = array();
$exclude = array();
$switches = array("+", "-");
for(
$i=0;
$i < count(
$input);
$i++){
$inst =
$input[
$i];
if(
$inst == "" && (
$i == "0" ||
$i == (count(
$input) - 1)) ){
$inst = "+"; }
if(in_array(
$inst,
$switches)){
$lswitch =
$inst;
}else{
if(
$inst != ""){
if(
$lswitch == "-"){
$exclude[] =
$inst;
}elseif(
$lswitch == "+"){
$include[] =
$inst;
}else{
$include[] =
$inst;
}
}
unset(
$lswitch);
}
} // end loop
$output = array("include" =>
$include, "exclude" =>
$exclude);
}else{
$output = array("include" => explode(" ", trim(
$input)));
}
return
$output;
} // end function
?>
Sorry for my somewhat messy and hard to follow code.
An example of the code would be:
<?php
$search = '"isearch"-"this"'
$do_search = parse_search(
$search);
print_r(
$do_search);
?>
will output:
Array
(
[include] => Array
(
[0] => isearch
)
[exclude] => Array
(
[0] => this
)
)
fraknot[at]ulfix[dot]com
16-Nov-2004 05:44
A function that returns the number of pages, id's, etc from a given range (this works when you specify a "printing-style range" like "1-3,5,7-9,11")
<?php
function range_count(
$array)
{
$first_split=explode(",",
$array);
$second_split=array();
for(
$i=0;
$i<count(
$first_split);
$i++)
$second_split[
$i]=explode("-",
$first_split[
$i]);
$num=array();
$number=0;
for(
$i=0;
$i<count(
$second_split);
$i++)
{
if(count(
$second_split[
$i])==2)
$num[
$i]=abs(
$second_split[
$i][1]-
$second_split[
$i][0])+1;
elseif(count(
$second_split[
$i])==1)
$num[
$i]=
$num[
$i]+1;
}
for(
$i=0;
$i<count(
$num);
$i++)
$number=
$number+
$num[
$i];
return(
$number);
}
echo range_count("1-3,5,7-9,11"); //8
echo range_count("5000"); //1
echo range_count("2003,2004"); //2
?>
ely at DONTSENDGARBGABE dot nauta dot com dot mx
05-Nov-2004 10:05
I've found very useful the csv_explode function posted by ng4rrjanbiah at rediffmail dot com. THANKS!
But, [ there is always a but d:o) ], it comes very handy to be able to skip the string delimiter with a backslash ("\"). Specially if you are using addslashes and stripslashes to create the CSV line.
Here's my two cents:
<?php
// Explode CSV string
function csv_explode(
$str,
$delim = ',',
$qual = "\"")
{
$skipchars = array(
$qual, "\\" );
$len = strlen(
$str);
$inside = false;
$word = '';
for (
$i = 0;
$i <
$len; ++
$i) {
if (
$str[
$i]==
$delim && !
$inside) {
$out[] =
$word;
$word = '';
} else if (
$inside && in_array(
$str[
$i],
$skipchars) && (
$i<
$len &&
$str[
$i+1]==
$qual)) {
$word .=
$qual;
++
$i;
} else if (
$str[
$i] ==
$qual) {
$inside = !
$inside;
} else {
$word .=
$str[
$i];
}
}
$out[] =
$word;
return
$out;
}
// Test...
$csv_str = 'a,"b",c,"this \"should\" work","and ""also"" this"';
echo "test: <pre>".print_r( csv_explode(
$csv_str), true )."</pre>";
?>
The result would be;
test:
Array
(
[0] => a
[1] => b
[2] => c
[3] => this "should" work
[4] => and "also" this
)
jtgalkowski at alum dot mit dot edu
20-Sep-2004 03:22
That explode returns FALSE when a null string is passed as the delimiting string can be unfortunate if all that wants doing is to explode a string into an array one "character" per array cell. This can be done using chunk_split at the cost of devoting a character to be used as an interim delimiter. Thus,
function flatExplodeUsing(
$safeCharacter,
$aString ) {
$a = explode(
$safeCharacter, chunk_split(
$aString, 1,
$safeCharacter ) ) ;
unset(
$a[strlen(
$aString)] ) ;
return(
$a ) ;
}
and
var_dump( flatExplodeUsing( "\xff", 'abcdef' ) ) ;
yields
array(6) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d"
[4]=> string(1) "e" [5]=> string(1) "f" }
ian at illumen dot co dot uk
24-Aug-2004 05:30
If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.
<?php
$str = '';
$foo = explode( ":",
$str );
print_r(
$foo );
$foo = split( ":",
$str );
print_r(
$foo );
$foo = preg_split( "/:/",
$str );
print_r(
$foo );
?>
In all three cases prints
Array
(
? ? [0] =>
)
This of course means that you must explicitly check to see if the value of the first element is blank, or must check to see if the string being split is blank.
aidan at php dot net
01-Jul-2004 10:45
If you're trying to parse CSV files, see fgetcsv()
hhabermann at pc-kiel dot de
09-Feb-2004 04:00
I needed a solution to implode and explode associative arrays. Now I use these two functions (there may be a better solution, but it works ;) ):
<?php
/**
* @name implodeAssoc(
$glue,
$arr)
* @description makes a string from an assiciative array
* @parameter glue: the string to glue the parts of the array with
* @parameter arr: array to implode
*/
function implodeAssoc(
$glue,
$arr)
{
$keys=array_keys(
$arr);
$values=array_values(
$arr);
return(implode(
$glue,
$keys).
$glue.implode(
$glue,
$values));
};
/**
* @name explodeAssoc(
$glue,
$arr)
* @description makes an assiciative array from a string
* @parameter glue: the string to glue the parts of the array with
* @parameter arr: array to explode
*/
function explodeAssoc(
$glue,
$str)
{
$arr=explode(
$glue,
$str);
$size=count(
$arr);
for (
$i=0;
$i <
$size/2;
$i++)
$out[
$arr[
$i]]=
$arr[
$i+(
$size/2)];
return(
$out);
};
?>
nanddam at zonnet dot nl
22-Dec-2003 07:07
Use explode to get the name(s) of the directorie(s) you're in
or make static links.
<?php
$script_name_array = explode("/", trim(
$_SERVER['SCRIPT_NAME']));
$ii = count(
$script_name_array)-1;
for(
$i=
$ii;
$i>0;
$i--){
print("
$i -- ".
$script_name_array[
$i]."<br>");
}
?>
nand . nl
siavash79_99 at yahoo dot com
20-Nov-2003 08:24
here is a tested case-insensitive explode I named it explodei().works cool :-)
<?php
function explodei(
$separator,
$string,
$limit = false )
{
$len = strlen(
$separator);
for (
$i = 0; ;
$i++ )
{
if ( (
$pos = stripos(
$string,
$separator )) === false || (
$limit !== false &&
$i >
$limit - 2 ) )
{
$result[
$i] =
$string;
break;
}
$result[
$i] = substr(
$string, 0,
$pos );
$string = substr(
$string,
$pos +
$len );
}
return
$result;
}
?>
If your php version is under 5, you'll need to add stripos() to your script.
See http://php.net/function.stripos
coroa at cosmo-genics dot com
17-Nov-2003 01: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");
ng4rrjanbiah at rediffmail dot com
31-Oct-2003 12:03
The improved CSV Explode function of "hhromic at udec dot cl" again has one limitation with MS Excel.
His version returns "" for """". But the expected result is " for """"
And so, I have modified his code with additional inside check.
<?php
// Explode CSV (MS Excel) string
function csv_explode(
$str,
$delim = ',',
$qual = "\"")
{
$len = strlen(
$str);
$inside = false;
$word = '';
for (
$i = 0;
$i <
$len; ++
$i) {
if (
$str[
$i]==
$delim && !
$inside) {
$out[] =
$word;
$word = '';
} else if (
$inside &&
$str[
$i]==
$qual && (
$i<
$len &&
$str[
$i+1]==
$qual)) {
$word .=
$qual;
++
$i;
} else if (
$str[
$i] ==
$qual) {
$inside = !
$inside;
} else {
$word .=
$str[
$i];
}
}
$out[] =
$word;
return
$out;
}
// Test...
$csv_str = 'a,"""","""",d,e,f';
print_r( csv_explode(
$csv_str) );
?>
HTH,
R. Rajesh Jeba Anbiah
ralfoide at yahoo dat com
14-Jul-2003 07:02
Using 1 or less for the "limit" may not yield the result you expect. I'm using PHP 4.1.2
I had surprising results when using explode() or split() with a "limit" of 0 or 1: in this case the returned array contains one entry with the full "remaining" string.
Ex:
$a = explode("/", "a/b/c", 1); var_dump(
$a);
=> array(1) { [0]=> string(5) "a/b/c" }
$a = explode("/", "a/b/c", 2); var_dump(
$a);
=> array(2) { [0]=> string(1) "a" [1]=> string(3) "b/c" }
Using limit=0 behaves as in limit=1 above.
It seems the implementation uses limit as the number of elements to return, including the "remaining string", whereas the doc seems to describe it as indicating the number of separators to process (i.e. the resulting array should contain limit+1 entries).
gnif at never_mind dot com
24-Jun-2003 05:01
This alters a parameter in a query string, if it doesn't exist adds it. May be useful to someone out there, it is a good example of the explode and implode functions. This code has been tested and proven working, there may allready be a function here that does this, I didn't have time to check all the posts.
<?php
function AlterQueryStr(
$querystr,
$param,
$value) {
$vars = explode("&",
$querystr);
$set = false;
for (
$i=0;
$i<count(
$vars);
$i++) {
$v = explode('=',
$vars[
$i]);
if (
$v[0] ==
$param) {
$v[1] =
$value;
$vars[
$i] = implode('=',
$v);
$set = true;
break;
}
}
if (!
$set) {
$vars[] =
$param . '=' .
$value;}
return ltrim(implode('&',
$vars), '&');
}
?>
Examples and Results:
AlterQueryStr('page=index&print=1&color=red', 'print', '0');
'page=index&print=0&color=red'
AlterQueryStr('page=index&print=1', 'color', 'red');
'page=index&print=1&color=red'
AlterQueryStr('', 'foo', 'bar');
'foo=bar'
--
http://spacevs.com
stefan at NOSPAM dot elakpistol dot com
22-May-2003 01:00
This function handles HTML-tags as "words", so each tag will become a single element in the array that is returned.
<?php
function explode_tags(
$chr,
$str) {
for (
$i=0,
$j=0;
$i < strlen(
$str);
$i++) {
if (
$str{
$i} ==
$chr) {
while (
$str{
$i+1} ==
$chr)
$i++;
$j++;
continue;
}
if (
$str{
$i} == "<") {
if (strlen(
$res[
$j]) > 0)
$j++;
$pos = strpos(
$str, ">",
$i);
$res[
$j] .= substr(
$str,
$i,
$pos -
$i+1);
$i += (
$pos -
$i);
$j++;
continue;
}
if (((
$str{
$i} == "\n") || (
$str{
$i} == "\r")) && (strlen(
$res[
$j]) == 0))
continue;
$res[
$j] .=
$str{
$i};
}
return
$res;
}
?>
johnnycobol at yahoo dot com
21-Mar-2003 07:13
If you need to parse Java properties using PHP, here is an example I wrote:
<?php
//Takes a multi-line string as input. Returns an array
//which can be accessed by property name.
function propertiesToArray(
$propertiesList)
{
$properties = explode("\n", trim(
$propertiesList));
$propArray = array();
foreach (
$properties as
$nameValue)
{
list(
$propName,
$propValue) = explode("=",
$nameValue);
$propArray[
$propName] =
$propValue;
}
return
$propArray;
}
$testprop = "property1=value1\nproperty2=value2\n\rproperty3=\n"
. "property4=value4";
$props = propertiesToArray(
$testprop);
foreach (
$props as
$key =>
$value)
{
echo "
$key =>
$value<br>\n";
}
?>
dan at boxuk dot com
14-Mar-2003 03:11
Here's a function I find useful from time to time.... When you're assigning the results of an explode() to a list(x,y,z) of values, you'll get an error/warning in PHP if your explode() didn't return the same number of arguments as your list... So you can use the following simple function to always return the correct number of elements in your array:
<?php
// explodeForce - like explode, but rather than just 'limit' the explosion to
// the number of values, it also ensures that this number of elements are
// present in the output array - v.useful for when assigning an explode
// to a list(
$a,
$b,
$c)
function explodeForce(
$sep,
$array,
$number_values,
$pad = '')
{
return array_pad(explode(
$sep,
$array,
$number_values),
$number_values,
$pad);
}
?>
tengel at fluid dot com
25-Feb-2003 09:02
Here's a little function similar to the above which will traverse a string, but pay attention to quotes inline. I.e., I needed to parse something like this into an array:
one two "third thing" "fourth thing" five
It's pretty slow, but it works.
<?php
function opt_explode(
$echar,
$str) {
if (strlen(
$echar) != 1 || strlen(
$str) == 0) {
return 0;
}
$str = trim(
$str);
// input string index counter
$idx=0;
// output array element counter
$arr=0;
while(
$idx < strlen(
$str)) {
if(
$str[
$idx] == '"') {
// quoted field
$idx++;
while (
$idx < strlen(
$str)) {
// look for ending quote
if(
$str[
$idx] == '"') {
$idx++;
$arr++;
break;
}
$newstrarr[
$arr] =
$newstrarr[
$arr] .
$str[
$idx];
$idx++;
}
} elseif (
$str[
$idx] ==
$echar) {
// normal delimiter, advance element
$arr++;
} else {
// must be normal char, tack onto current element
$newstrarr[
$arr] =
$newstrarr[
$arr] .
$str[
$idx];
}
$idx++;
}
return
$newstrarr;
}
?>
jasenko at get2net dot dk
19-Feb-2003 11:42
This is example of converting strings to proper case (as we know it from VB). It shows use of PHP string functions explode(), substr() and trim() along with case converting functions.
It's quite simple !
<?php
function properCase(
$strIn)
{
$arrTmp = explode(" ", trim(
$strIn));
for(
$i=0;
$i < count(
$arrTmp);
$i++)
{
$firstLetter = substr(
$arrTmp[
$i],0,1);
$rest = substr(
$arrTmp[
$i],1,strlen(
$arrTmp[
$i]));
$arrOut[
$i] = strtoupper(
$firstLetter).strtolower(
$rest);
}
for(
$j=0;
$j < count(
$arrOut);
$j++)
$retVal .=
$arrOut[
$j]." ";
return trim(
$retVal);
}
?>
Hope this can be usefull to someone (I know it was to me ...).
lennartg at web dot de
15-Feb-2003 12:52
Use this function to assign keys to the result array instead of numbered entries.
The
$keys array must be a numeric array and must have same size entries in the
$string.
<?php
function explodeKeys(
$separator,
$string,
$keys) {
$res = explode(
$separator,
$string);
if (@is_array(
$res) && @is_array(
$keys)) {
$size = sizeof(
$res);
if (
$size == sizeof(
$keys)) {
for (
$i=0;
$i <
$size;
$i++) {
$res[
$keys[
$i]] =
$res[
$i];
unset(
$res[
$i]);
}
return
$res;
}
}
return false;
}
?>
davidrickard at hotmail dot com
26-Oct-2002 02:32
[Ed. Note: Windows browsers insert \r\n, but other platforms have their own line endings. Most UNIX-like systems will use \n. Try <?php str_replace("\r", null,
$string); ?> and then explode()ing.]
If you want to get some form data entered in the form
Item1
Item2
Item3
At the other end you need to use
explode("\r\n",
$_POST['fieldname'])
rather than just \n .
jeremy at fishbowlrecords dot com
23-Oct-2002 03:58
While explode() and implode() are helpful functions, I found I needed to write additional functions to correctly handle two dimensional arrays. Here are the two functions:
These functions based on code from <peter at int8 dot com>.
<?php
// just as double_explode functions akin to explode, so too does
// double_implode to implode
function double_implode(
$first_break,
$second_break,
$array)
{
$string = "";
$k=0;
$num_length = count(
$array);
foreach (
$array as
$key =>
$value)
{
// if the element of the main array is an array
if (is_array(
$array[
$key]))
{
// append the string of the converted arary to
// the string being constructed of the whole
// main array
$string .= implode(
$second_break,
$array[
$key]);
}
else
{
// append the element to the string
$string .=
$array[
$key];
}
$k++;
//change here!
// append the delimiting character to the string
if (
$k<
$num_length)
$string .=
$first_break;
}
return
$string;
}
// this is a replacement for the internal explode function so that
// strings representing 2D arrays (ie matrices) maybe made again
// into their array format
function double_explode(
$first_break,
$second_break,
$string)
{
// creates array based on the first division character
$array = explode(
$first_break,
$string);
// loops through the created array in search of any strings
// that need to be converted to arrays
for (
$k=0;
$k < count(
$array);
$k++)
{
// the number of times the second division character
// is present
$count = substr_count(
$array[
$k],
$second_break);
// if the second division character is present; ie,
// if the string needs to be converted to an array
if (
$count>0)
{
// creates array from string and puts it in
// the main array where the string was
$array[
$k] = explode(
$second_break,
$array[
$k]);
}
}
return
$array;
}
?>
Notice the "if (
$k<
$num_length)" check near the bottom. What I found is that without that, any string created would have an extra character at the end, and when exploded would have an extra (empty) array cell at the end. So, now I can do something like
if (
$arraybeforeimplode==
$arrayafterexplode)
and they will be equal, whereas before they would test as not being equal. I hope that made sense. Thanks!