PHP/Data Structure/explode

Материал из Web эксперт
Перейти к: навигация, поиск

Breaking Strings into Arrays with explode()

 
<?php
    $start_date = "2000-01-12";
    $date_array = explode ("-",$start_date);
?>



Display year an individual was born

 
<?php 
$expdate = explode ("-","1979-06-23"); 
echo $expdate[0] . ",";
echo $expdate[0]; 
?>



explode( ) function converts a string into an array using a separator value

 
//array explode ( string separator, string input [, int limit] )
<?
    $oz = "Lions and Tigers and Bears";
    $oz_array = explode(" and ", $oz);
?>



explode() function divides string into various elements, returning these elements in an array.

 
The syntax is: array explode (string separator, string string [, int limit])
<?
$info = "A|b|i";
$user = explode("|", $info);
print $user;
?>



explode.php

 
<?php
$summary = <<< summary
line 1
line 2
<a href="http://www.php.net">PHP 5</a>
summary;
$words = sizeof(explode(" ",strip_tags($summary)));
echo "Total words in summary: $words";
?>



Generating an ID with microtime()

 
<?php
list($microseconds,$seconds) = explode(" ",microtime());
$id = $seconds.$microseconds.getmypid();
?>



Processing variable-length text fields

 
<?php
$delim = "|";
$fh = fopen("books.txt","r") or die("can"t open: $php_errormsg");
while (! feof($fh)) {
    $s = rtrim(fgets($fh));
    $fields = explode($delim,$s);
}
fclose($fh) or die("can"t close: $php_errormsg");
?>



Reading and Writing Comma-Separated Data

 
<?php
  $commafile = "data.txt";
  if (file_exists ($commafile)){
    $rows = file ($commafile);
    for ($i = 0; $i < count ($rows); $i++){
      $exprow = explode (",", $rows[$i]);
      echo "ID: " . $exprow[0] . "<br />";
      echo "Name: " . $exprow[1] . "<br />";
      echo "Author: " . $exprow[2] . "<br />";
      echo "<hr />";
    }
  } else {
    echo "File does not exist.";
  }
  $idarray = array ("1","2","3");
  $namearray = array ("Book 1","Book 2","Book 3");
  $authorarray = array ("Author","Author","Author");
    
  $newfile = "data.txt";
  try {
    if ($readfile = fopen ($newfile, "w")){
      for ($i = 0; $i < count ($idarray); $i++){
        $writestring = $idarray[$i] . "," . $namearray[$i] . "," . $authorarray[$i] . "\n";
        fwrite ($readfile, $writestring);
      }
      fclose ($readfile);
    } else {
      throw new exception ("Sorry, the file could not be opened.");
    }
  } catch (exception $e) {
    echo $e->getmessage();
  }
?>



Using explode() with date()

 
<?php
$ar = explode("|",date("h a|F d, Y"));
print "It"s after $ar[0] on $ar[1]";
?>



Using the explode() Function

 
<?php
    $input_string = "this is a test.";
    $pieces = explode(",", $input_string);
    echo "Names in List: <BR/>\n";
    foreach($pieces as $name) {
        echo trim($name) . "<BR/>\n";
    }
?>