Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 68
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Po wysłaniu do Dariusza problemu jeszcze nie opisanego w poradach, odpowiedź pojawia się na stronach już po 24 godzinach. To jedna z najważniejszych zalet serwisu! Za około 100 złotych rocznie mam profesjonalnego i doświadczonego konsultanta od technologii internetowych! Polecam serwis z poradami każdemu webmasterowi, niezależnie od stażu pracy i umiejętności.

Paweł Kowalski
grupa hiperMEDIA.pl

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

explode

(PHP 3, PHP 4, PHP 5)

explode -- Split a string by string

Description

array explode ( string separator, string string [, int limit] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If separator is an empty string (""), explode() will return FALSE. If separator contains a value that is not contained in string, then explode() will return an array containing string.

If the limit parameter is negative, all components except the last limit are returned. This feature was added in PHP 5.1.0.

Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the separator argument comes before the string argument.

Notatka: The limit parameter was added in PHP 4.0.1

Przykład 1. explode() examples

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo
$pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo
$user; // foo
echo $pass; // *

?>

Przykład 2. limit parameter examples

<?php
$str
= 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit
print_r(explode('|', $str, -1));
?>

Powyższy przykład wyświetli:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Notatka: Ta funkcja jest bezpieczna dla danych binarnych.

See also preg_split(), spliti(), split(), and implode().




User Contributed Notes

STaRDoGGCHaMP
11-Jan-2006 04:07

Following code:

<?php

$string
= "12345678";
$explode = explode("5",$string);

for(
$i = 0; $i <= strlen($string); $i++){

   if(isset(
$explode[$i])){

     echo
"The variable \$explode[$i] exists! <br>";

     echo
$explode[$i] . "<br><br>";   

   }

   else{

       echo
"The variable \$explode[$i] doesn't exist!<br><br>";
 
   }

}

?>

produce this output:

The variable $explode[0] exists!
1234

The variable $explode[1] exists!
678

The variable $explode[2] doesn't exist!

The variable $explode[3] doesn't exist!

The variable $explode[4] doesn't exist!

The variable $explode[5] doesn't exist!

The variable $explode[6] doesn't exist!

The variable $explode[7] doesn't exist!

The variable $explode[8] doesn't exist!


sbc at mail dot bg
27-Dec-2005 06: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!


sbc at mail dot bg
26-Dec-2005 09:18

Hello, this is my first post and the code is not very clean, but it's working and may help someone  :-)
Thanx to the function of "contact_trieu at hotmail dot com"

So, if you have long string, it will hyphenate it into lines with specific length:

<? function hyphenate_text($text)
{
  
$length = 20;            //  Length of the rows
  
$hyphenate = "<br>";    //  Hyphenate char
  
$startcount = 0;
  
$followcount = 0;
  
$c = 1;
  
   for (
$i=0; $i<$c; $i++)
   {
      
$words = explode(' ', $text);
      
$c = count($words);
        
$wcount = 0;
      
$curindex = 0;
       foreach(
$words as $value)
       {
           if (
$followcount > $startcount || $followcount==0)
           {
              
$wcount += strlen($value)+1;       
               if(
$wcount>$length-strlen($hyphenate)){
                   break;
               }
              
$curindex++;
           }
           else{
          
$followcount++;}
       }
      
$med_line = implode(' ', array_slice($words, $startcount, $curindex)) . $hyphenate;
      
$startcount += $curindex;
      
$followcount += $startcount;
       if (
$med_line == $hyphenate) {$c=0;} 

       echo
$med_line;        // Drow Line
  
}   
}
?>


michael dot martinek at gmail dot com
07-Dec-2005 01: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 09: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_lstr_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 02: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."&#39; ".$remaining_inches."&quot;";

  return $height;
}


fsnirl.hinny at gmail.com
22-Oct-2005 03: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 10: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 02: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;
   }
?>


michael dot martinek at gmail dot com
15-Oct-2005 02:32

>> richardkmiller at gmail dot com

I was also looking for an explode() function that would allow you to specify an encapsulation character. I went ahead and developed one of my own based roughly off yours.

My version of it is faster in the sense that:
- It does not do string = string + character. This creates a new copy in memory each time.
- It does not calculate the length of the source string on each for() iteration. Memory/processing time trade-off.

Additionally, it retains the same features provided through your explode2() function. Namely, the fact that you can specify your own delimiter character and allow for encapsulation characters to be passed. My version will allow you to specify your own encapsulation character.

I've run 4 tests on my Linux Server, running 800MHz w/ 512 SD-RAM. Linux beta 2.6.12-1.1447_FC4 #1, PHP 5.0.4 (cli) (built: Aug 17 2005 09:53:54). The average of the time results are as follows:

explode_quote average time 0..500000  76.704669952393
explode2() average time 0..500000  113.08254504204

The time calculation is done with a microtime() before the 500,000 loop and then microtime() - startTime upon completion. Four tests were run on each version, and the averages used.

Here's the code:

<?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)
              
$insideEncap = !$insideEncap;
           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;
   }
?>

If anyone decides to run any of their own speed tests, ensure to use set_time_limit(0), otherwise it'll stop after your configured max_execution_time.

Rather than string = string + data, this version will just save the position of the most recent delimiter. Once it hits another delimiter, it will copy a section of the string from the previous-found delimiter. The result is one memory allocation for the string, rather than many for s .= d.


hardy at mapscene dot de
07-Oct-2005 02: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
17-Sep-2005 08: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 04: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 02: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 04:44

Here's an even better last word function:

function lastword($theString)
{
   $stringParts = explode(" ", $theString);
   return array_pop($stringParts);
}


mikeshoup at gmail dot com
15-Jul-2005 06: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
07-Jul-2005 08: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 02: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 02: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 02: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 07: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
15-Jun-2005 09: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 02: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 05: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 10: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 02: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 02: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 09: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
11-Apr-2005 09: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 06: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
23-Feb-2005 10:20

Also, it seems any array element (at least using explode) is limited to 255 characters.


woltersware at ish dot de
28-Jan-2005 08: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 12: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 02: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 03: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 01: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 11: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
20-Nov-2004 08: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
15-Nov-2004 09: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 02: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
19-Sep-2004 08: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 10: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
(

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt