 |
explode (PHP 3, PHP 4, PHP 5) explode -- 使用一个字符串分割另一个字符串 描述array explode ( string separator, string string [, int limit] )
此函数返回由字符串组成的数组,每个元素都是
string
的一个子串,它们被字符串
separator
作为边界点分割出来。如果设置了
limit
参数,则返回的数组包含最多
limit
个元素,而最后那个元素将包含
string
的剩余部分。
如果
separator
为空字符串(""),explode()
将返回 FALSE。如果
separator
所包含的值在
string
中找不到,那么
explode()
将返回包含 string
单个元素的数组。
如果
limit
参数是负数,则返回除了最后的
limit
个元素外的所有元素。此特性是 PHP 5.1.0 中新增的。
由于历史原因,虽然 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; // *
?>
|
|
例子 2. limit 参数示例
<?php $str = 'one|two|three|four';
// 正数的 limit print_r(explode('|', $str, 2));
// 负数的 limit print_r(explode('|', $str, -1)); ?>
|
以上示例将输出:
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
) |
|
参见
preg_split()、spliti()、split()
与 implode()。
bfpdevel at gmail dot com
27-May-2006 05:44
This is a entire modification of the markus function
I don't know if that function work fast with long strings, I only test it with a max of 600 characters and work very fast.
This function have a minor bug, if someone know how to fix them, wellcome.
at the first line, I change the cuotes for a "not very used" character. But if that character are used in the $string, them we have a problem.
The line is: $op = array("\\'"=>"~", "\\\""=>"");
Sorry my english
<?php
function quote_explode( $delim, $string, $encap = '"' )
{
$op = array("\\'"=>"~", "\\\""=>"");
foreach($op as $key => $val)
$string = str_replace($key, $val, $string);
$localstr = "";
$s = str_split($string);
for($i=0; $i < count($s); $i++)
{
if($s[$i] == $encap && (!$action || $action == "close"))
$action = "open";
else if($s[$i] == $encap && $action == "open")
$action = "close";
if($s[$i] == $delim && !$action)
{
foreach($op as $key => $val)
$localstr = str_replace($val, $key, $localstr);
$r[] = $localstr;
$localstr = "";
continue;
}
if($action == "open" && $s[$i] != $encap)
$localstr .= $s[$i];
else if($action == "close")
$action = false;
else if($s[$i] != $encap)
$localstr .= $s[$i];
}
$r[] = $localstr;
return $r;
}
?>
webmaster at saund-web dot com
14-Mar-2006 02:20
If you want to split a price (float) into pounds and pence.
or dollors and cents etc etc.
$price = "6.20";
$split = explode(".", $price);
$pound = $split[0]; // piece1
$pence = $split[1]; // piece2
echo "£ $pound . $pence\n";
markus dot schabel at tgm dot ac dot at
15-Feb-2006 06:29
My version looks like the following:
<?php
/**
* Explode a string by delimiters, but ignore delimiters inside encapsulation.
*
* This function works like the explode() function, but takes care that
* delimiters inside encapsulated parts are ignored. This is useful for CSV
* files, where the parts may be encapsulated by " or ', and any delimiter
* between two encapsulation characters is part of the string, so this part
* cannot be exploded.
* Note however, when reading data from a CSV file, the PHP function fgetcsv()
* should be used.
*
* @param string $delim is the delimiter that should be used for splitting.
* @param string $string is the string that should be splitted.
* @param string $encap is the encapsulation character.
*
* @return array of string that contains the splitted parts.
*/
function quote_explode( $delim, $string, $encap = '"' ) {
$parts = explode( $delim, $string );
$correctParts = array();
$correctIndex = 0;
$insideEncaps = false;
foreach ( $parts as $part ) {
$numEncaps = substr_count( $part, $encap );
if ( !$insideEncaps ) {
switch ( $numEncaps ) {
case 1:
$correctParts[$correctIndex] = str_replace( $encap, '', $part );
$insideEncaps = true;
break;
case 0:
case 2:
$correctParts[$correctIndex++] = str_replace( $encap, '', $part );
break;
default:
echo 'Found more than 2 encapsulations - this should not happen!';
}
} else {
switch ( $numEncaps ) {
case 0:
$correctParts[$correctIndex] .= ';'.str_replace( $encap, '', $part );
break;
case 1:
$correctParts[$correctIndex++] .= ';'.str_replace( $encap, '', $part );
$insideEncaps = false;
break;
default:
echo 'Found more than 2 encapsulations - this should not happen!';
}
}
}
return $correctParts;
}
?>
However, I just replaced it with fgetcsv(). There really should be a see-also link to the fgetcsv() function. ;-))
sbc at mail dot bg
28-Dec-2005 01:11
I`m sorry, the previous function was very slow because it uses expandable number of iterations, and does not hyphenate correctly.
so use this one, because it uses only 1 iteration!!!
Also keep in mind that the function hyphenate whole words.
<?
function hyphenate_text($text)
{
$length = 70; // Length of the rows
$hyphenate = '<br>'; // Hyphenate char
$startcount = 0;
$curindex = 0;
$wcount = 0;
$words = explode(' ', $text);
$c = count ($words);
$hyphe = array();
for($i=0; $i<=$c; $i++)
{
$value = $words[$i];
$wcount += strlen($value)+1;
if($wcount>$length-strlen($hyphenate) || $i==$c)
{
if ($curindex==0) // If there is word bigger than the length
{
$curindex=1;
$i++;
}
$med_line = implode(' ', array_slice($words, $startcount, $curindex)) . $hyphenate;
array_push ($hyphe, $med_line); // Add Line
$wcount = 0;
$startcount += $curindex;
$curindex = -1;
if ($i == $c)
break;
$i--;
}
$curindex++;
}
return $hyphe;
}
?>
You have to add String, and the function returns array of lines!
michael dot martinek at gmail dot com
07-Dec-2005 08:37
The explodei function gave me an idea. I did some modifications to it, and appear to have made it a bit faster. My time-tests aren't scientific either, I just put it in a loop and run it a couple thousand times (more or less, depending on how much data is being processed.)
In the original explodei posted, I had to comment out the "if(function_exists("str_ireplace"))" section, as my PHP version is >5; and this is a function being done for <5. :)
<?php
function explodei($ASeperator, $ASource) {
$ASeperator = strtolower($ASeperator);
//also create a case insensitive source in memory
$x_insensitive = strtolower($ASource);
//get result based off insensitive matches.
$x_data = explode($ASeperator, $x_insensitive);
//iterate each item and transfer over the fields based on length
$x_position = 0;
//don't keep calling strlen() in a loop on a consistent source.. icky.
$x_sep_len = strlen($ASeperator);
//iterate all elements obtained via explode() assigned to $x_data
foreach ($x_data as $myElement) {
//How long is this particular element?
$x_element_length = strlen($myElement);
//create new result element, we have the position and length, grab it from
//the ORIGINAL source, so we don't pass along non-original info.
$retval[] = substr($ASource, $x_position, $x_element_length);
//increase position by length of seperator, and length of this element.
$x_position += $x_element_length + $x_sep_len;
}
//return our results
return $retval;
}
?>
The results! In a PHP <5 version:
Testing source:
<?php
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//Be careful! This increases exponentially. :)
for ($x=0,$x_source="TEST|";$x<16;$x++) $x_source .= $x_source;
echo "\$x_source length: " . strlen($x_source) . "\n";
$x_micro_start = microtime_float();
//increase or decrease $x<10 to whatever.
//Don't do many iterations on a high $x value above.
for ($x = 0; $x<2; $x++)
$myResult = explodei('|', $x_source);
$x_micro_stop = microtime_float();
$x_micro_time = $x_micro_stop - $x_micro_start;
echo "Time: {$x_micro_time} seconds.\n";
?>
The original explodei:
akede:/home/akede # php -f ip2loc.php
$x_source length: 327680
Time: 151.550167084 seconds.
My version:
akede:/home/akede # php -f ip2loc.php
$x_source length: 327680
Time: 0.943643808365 seconds.
The reason it's faster? Because it relies on built-in functions more than the original. Explode does the "hard work" and finds all the positions we're going to need. In the original, it uses the scripting environment to iterate the entire source string, .. hmm. Actually, if I understand that right, it looks like it actually is going off a 1-character seperator in the original source. I guess that works. Explode(), AFAIK supports strings for seperators. Anyway, it works. Write something faster, play with it, use it, whatever. It's all fun-- have fun!
kroczu at interia dot pl
22-Nov-2005 04:32
case-insensitive version of explode()
<?
function explodei($separator, &$txt){
// working in PHP 5 (fast) ///////////////////////////
if(function_exists("str_ireplace")){
$separator_l=strtolower($separator);
return explode($separator_l, str_ireplace($separator, $separator_l, $txt));
}
// PHP < 5 (slow) ///////////////////////////////////
$txt_l=strlen($txt);
$separator_l=strlen($separator);
$separator=strtolower($separator);
$j=0;
$row=0;
$stop=false;
$start=0;
for($i=0; $i<$txt_l; $i++){
if($txt[$i]==$separator[$j]){
if($stop===false) $stop=$i;
$j++;
if($j==$separator_l){
$tab[$row]=substr($txt, $start, $stop-$start);
$row++;
$i=$start=$stop+$separator_l;
$stop=false;
$j=0;
}
}
elseif($stop!==false){
$i=$stop+1;
$stop=false;
$j=0;
}
}
$tab[$row]=substr($txt, $start);
return $tab;
}
?>
sean at aliencreations dot com
06-Nov-2005 09:01
Here's a simple function to convert someone's height in inches to a feet/inch ratio using explode():
function get_height($inches)
{
//divide by 12 to get inches
$feet = $inches/12;
//round decimal so we can divide by 100 and use as percent
$feet = round($feet, 2);
// separate whole from decimal
$parts = explode(".", $feet);
$whole_feet = $parts[0];
//turn remaining into percent of 12
$remaining_inches = round(($parts[1]/100)*12);
$height = $whole_feet."' ".$remaining_inches.""";
return $height;
}
fsnirl.hinny at gmail.com
22-Oct-2005 09:27
Correct me if I'm wrong, but I think this way of doing the explode_quote or explode2 function is much quicker if you always want to mark words by quotes and a space is the delimeter to break things on otherwise. Using php's built in functions usually makes things run a lot faster.
<?php
function explode_quotes($AString) {
$words = wordwrap($AString,3);
$exploded = explode("\n",$words);
$exploded = str_replace(chr(26),' ',$exploded);
return $exploded;
}
?>
I don't know what benchmark you are talking about for the other posts since they are never really described, but I just put a for loop around each one and ran the for loop 400000 times and here is the time difference between my explode_quotes and the first posted explode_quote
Start 1: 1129947556
End 1: 1129947559
Total 1: 3 seconds
Start 2: 1129947559
End 2: 1129947584
Total 2: 25 seconds
Not very scientific, but the advantage is clear.
Note, my email address is obfuscated by moving my left hand one key position to the right.
britz_pm at hotmail dot com
19-Oct-2005 04:23
PLEASE NOTE I HAD TO BREAK SOME LINES CAUSE OF WORDWRAP() WAS NOT HAPPY :(
Well i thought of making some versions of explode/implode
functions with can do any depth of multi-dimensional arrays
with or without keeping the keys
make/change the defaults as you need them
as for error checking i did not add any because would probably
make it take longer to run add em if you please
Code:
<?php
function mul_dim_implode($curarray,$startglue,$endglue,
$withkeys=false,$startkeyglue=null,$endkeyglue=null,$level=0) {
foreach($curarray as $curkey => $curvalue) {
if (is_array($curvalue)) {
$curvalue = mul_dim_implode($curvalue,$startglue,$endglue,
$withkeys,$startkeyglue,$endkeyglue,$level+1);
}
if (!isset($retu)) {
if ($withkeys) {
$retu = $curkey.$startkeyglue.$level.$endkeyglue.$curvalue;
} else {
$retu = $curvalue;
}
} else {
if ($withkeys) {
$retu .= $startglue.$level.$endglue.$curkey.
$startkeyglue.$level.$endkeyglue.$curvalue;
} else {
$retu .= $startglue.$level.$endglue.$curvalue;
}
}
}
return $retu;
}
function mul_dim_explode($curstring,$startglue,$endglue,
$withkeys=false,$startkeyglue=null,$endkeyglue=null,$level=0) {
if (strstr($curstring,$startglue.$level.$endglue)) {
$eacharay = explode($startglue.$level.$endglue,$curstring);
foreach ($eacharay as $curstr) {
if ($withkeys) {
$temp = explode($startkeyglue.$level.$endkeyglue,$curstr);
$retu[$temp[0]] = mul_dim_explode($temp[1],$startglue,$endglue,
$withkeys,$startkeyglue,$endkeyglue,$level+1);
} else {
$retu[] = mul_dim_explode($curstr,$startglue,$endglue,
$withkeys,$startkeyglue,$endkeyglue,$level+1);
}
}
} else {
return $curstring;
}
return $retu;
}
?>
Example:
<?php
$array = array('a' => 'aa', 'b' => 'bb',
'c' => array('d' => 'dd', 'e' => 'ee',
'f' => array('g' => 'gg', 'h' => 'hh')));
$plode = mul_dim_implode($array,"-[","]-");
$keyplode = mul_dim_implode($array,"-[","]-",true,"={","}=");
echo($plode);
echo("\n<br/>\n");
echo($keyplode);
$unplode = mul_dim_explode($plode,"-[","]-");
$keyunplode = mul_dim_explode($keyplode,"-[","]-",true,"={","}=");
echo("\n<pre>\n");
echo("Before:\n");
print_r($array);
echo("After:\n");
print_r($unplode);
print_r($keyunplode);
echo("</pre>");
?>
Output:
aa-[0]-bb-[0]-dd-[1]-ee-[1]-gg-[2]-hh
a={0}=aa-[0]-b={0}=bb-[0]-c={0}=d={1}=dd
-[1]-e={1}=ee-[1]-f={1}=g={2}=gg-[2]-h={2}=hh
Before:
Array
(
[a] => aa
[b] => bb
[c] => Array
(
[d] => dd
[e] => ee
[f] => Array
(
[g] => gg
[h] => hh
)
)
)
After:
Array
(
[0] => aa
[1] => bb
[2] => Array
(
[0] => dd
[1] => ee
[2] => Array
(
[0] => gg
[1] => hh
)
)
)
Array
(
[a] => aa
[b] => bb
[c] => Array
(
[d] => dd
[e] => ee
[f] => Array
(
[g] => gg
[h] => hh
)
)
)
Enjoy. ;p
michael dot martinek at gmail dot com
15-Oct-2005 08:51
Re: My Last Post
I left an important part of my last post out. My previous explode_quote method will leave the encapsulation characters in the resulting arrays.
The time average on 4 executions for this modification is 68.66882109642. (On explode() it's 3 seconds, which has almost made me want to write a module for things like this, so they can be binary-compiled.
Anyway, here's the code to leave out encapsulation characters:
<?php
function explode_quote($ADelim, $AString, $AEncap = '"') {
$retval = array();
//if we have an empty string, don't even bother processing
if (empty($AString))
return $retval;
//calculate source length and initialize some variables
$srcLength = strlen($AString);
$insideEncap = false;
//0..X string indexing in PHP, we'll be reading +1
$lastPos = -1;
for ($x=0;$x<$srcLength;$x++) {
if ($AString[$x]==$AEncap) {
if (!($insideEncap = !$insideEncap)) {
$retval[] = substr($AString, $lastPos+2, $x-$lastPos-2);
$lastPos = ++$x;
}
}
elseif (!$insideEncap && $AString[$x]==$ADelim) {
$retval[] = substr($AString, $lastPos+1, $x-$lastPos-1);
$lastPos = $x;
}
}
//if string doesn't end with delimiter, then throw remaining data to result
if ($lastPos!=$srcLength)
$retval[] = substr($AString, $lastPos+1, $srcLength);
return $retval;
}
?>
hardy at mapscene dot de
07-Oct-2005 08:17
//new quick lastword-function demonstration of the fastest way possible!
if (!function_exists('microtime_float')) {
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
function lastwordOLD($string,$seperator=" ") {//last word of an string
$array = explode($seperator, $string);
$number = count($array);
if($number>0) {
$number--;
return $array[$number];
}
return;
}
//low memory/cpu/parsetime-usage-version of lastword
function lastword($string,$seperator=" ") {//last word of an string
return substr($string,strrpos($string,$seperator));
}
//letz check how good is the new function instead of the old...
$time_start = microtime_float(true);
print "<br><br>lastwordOLD:";
print "<br>needle included: ".lastwordOLD("hans peter susi luci");//output needle included: luci
print "<br>needle not included: ".lastwordOLD("hans;peter;susi;luci");//output needle not included: hans;peter;susi;luci
print "<br>runtime-usage x10000: ";
$aa=0;
while($aa<10000){
$aa++;
$request=lastwordOLD("hans peter susi luci");
$request=lastwordOLD("hans;peter;susi;luci");
}
$time_end = microtime_float();
$timeOLD = $time_end - $time_start;
print $timeOLD;
$time_start = microtime_float(true);
print "<br><br>lastword(new):";
print "<br>needle included: ".lastword("hans peter susi luci");//output needle included: luci
print "<br>needle not included: ".lastword("hans;peter;susi;luci");//output needle not included: hans;peter;susi;luci
print "<br>runtime-usage x10000: ";
$aa=0;
while($aa<10000){
$aa++;
$request=lastword("hans peter susi luci");
$request=lastword("hans;peter;susi;luci");
}
$time_end = microtime_float();
$time = $time_end - $time_start;
print $time;
//the result is...
print "<br><br>you spare with this script and using new function instead of old: ".($timeOLD-$time)." sec.";
//you will see the parsetime of new function procedere will be circa a half of the old!
//
//result of my webserver , running on an pentium4 2800mhz with suse9
//
//lastwordOLD:
//needle included: luci
//needle not included: hans;peter;susi;luci
//runtime-usage x10000: 0.15616607666
//
//lastword(new):
//needle included: luci
//needle not included: hans;peter;susi;luci
//runtime-usage x10000: 0.0851180553436
//
//you spare with this script and using new function instead of old: 0.0710480213165 sec.
jeppe at bundsgaard dot net
18-Sep-2005 02:08
In version 5.05 (I have heard it is the same in 5.1) I suddenly got the error "only variables can be passed by reference" in connection to "array_pop(explode())" - it affects a lot of other combinations too (array_shift, array_keys, list etc).
The solution is simple (and it is possible to do a global search and replace):
replace array_pop(explode()) with array_pop($dummyarr=explode()).
ployola at kinetica dot cl
26-Jul-2005 10:52
Function to format a date:
function formato_fecha($fecha){
$arr = explode("-", $fecha);
$fecha=$arr[2]."/".$arr[1]."/".$arr[0];
return $fecha;
}
x403 at yandex dot ru
24-Jul-2005 08:09
For parsing URL better use Preg_split with flag PREG_SPLIT_NO_EMPTY because Explode or Split functions set empty array elements. For example:
$parts = preg_split("/\//i", $_SERVER["REQUEST_URI"], -1, PREG_SPLIT_NO_EMPTY);
result: Array ( [0] => mix [1] => exhibit )
Explode("/",$_SERVER["REQUEST_URI"] )
result: Array ( [0] => [1] => [2] => mix [3] => exhibit )
jeremymcanally at gmail dot com
21-Jul-2005 10:44
Here's an even better last word function:
function lastword($theString)
{
$stringParts = explode(" ", $theString);
return array_pop($stringParts);
}
mikeshoup at gmail dot com
16-Jul-2005 12:06
Its worthy to note that the . and .. directories are also listed. If you don't want them, I do a check like:
<?php
while(false !== ($file = readdir($directory)))
{
if($file == '.' || $file == '..') continue;
/* Do Stuff Here */
}
?>
AussieDan
08-Jul-2005 02:12
Here is an expanded version of the csv_explode function which can parse a string consisting of multiple csv rows.
<?php
function csv_parse($str,$f_delim = ',',$r_delim = "\n",$qual = '"')
{
$output = array();
$row = array();
$word = '';
$len = strlen($str);
$inside = false;
$skipchars = array($qual,'\\');
for ($i = 0; $i < $len; ++$i) {
$c = $str[$i];
if (!$inside && $c == $f_delim) {
$row[] = $word;
$word = '';
} elseif (!$inside && $c == $r_delim) {
$row[] = $word;
$word = '';
$output[] = $row;
$row = array();
} else if ($inside && in_array($c,$skipchars) && ($i+1 < $len && $str[$i+1] == $qual)) {
$word .= $qual;
++$i;
} else if ($c == $qual) {
$inside = !$inside;
} else {
$word .= $c;
}
}
$row[] = $word;
$output[] = $row;
return $output;
}
?>
www.AllportPC.com
07-Jul-2005 08:34
I was trying to make it simple for a user to enter values in 1 text field and save them in a database and then the database convert it to a drop down. I wrote this code and it works great.
<select name="select" size="1">
<?php $body = "value1;value2;value3;value4";
$body1 = explode(";", $body);
$body1Count = count($body1)-1;
$body1Start = 0;
do {
echo '<option value="' . $body1[$body1Start] . '">' . $body1[$body1Start] . '</option>';
$body1Start = $body1Start + 1;
} while ($body1Count >= $body1Start); ?>
</select>
janklopper.at.gmail.dot.com
28-Jun-2005 08: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 08: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 01: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;
}
?>
m_b
01-Jun-2005 08: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
17-May-2005 11: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 04: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 08: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 08: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 03: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 03: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 01: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 05:20
Also, it seems any array element (at least using explode) is limited to 255 characters.
woltersware at ish dot de
29-Jan-2005 03: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 07: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 09: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 10: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 08: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 06: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 03: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 04: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 09: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 02: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 04: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 09:45
If you're trying to parse CSV files, see fgetcsv()
hhabermann at pc-kiel dot de
09-Feb-2004 03: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 06: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 07: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 12: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
30-Oct-2003 11: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 06: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 04: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 12: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 06: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 02: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 08: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 10: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
14-Feb-2003 11: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 01: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 02: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!
|  |