Friday, February 18, 2011

How-to-split-a-text--->PHP

Assalamu'alaikum dan selamat sejahtera

Selamt pagi!morning!ohayou!

So,for this post,we will learn on how to split a text in PHP ,here is the quick example:

$line="Group 1,200,250,150,100,700";

but we want print it to be like this:


Group 1
200
:250
150
100
700

So,here is the code:

<?PHP
$line = "Group 1,200,250,150,100,700";
$line = explode(",",$line);
print $line[0];
?>

okey,let see...we got the new code again..here is:
explode(",",$line);

 so,explode is function to split the variable...so,inside the round bracket,we got a comma and variable name.we know that variable name is used for reference but for comma is to tell the explode function,that in order to split the text,you must read until you find the comma,then the next character will be split.so far okay?
 another explanation...is order to use this function,you must have two thing...one separator,one is variable..so,in this case,we declare $line  like this:


$line = "Group 1  ,  200  ,   250  ,   150   ,   100  ,   700";

 
so,we got the variable and the separator is "," is comma because it separate the word "Group 1" from other number :200,250,150,100,700.so far okey?hahaha

but the browser print "Group 1" ryte?it is because when the variable "$line" is split (using explode() function,the $line will change to an array that why in order to print it,we must put "[ ]".So,to print all,we can use for loops or this method:


print_r($line);

Then change the declaration of $line to be like this:

$line = "Group 1,Jan:1,Feb:2,Mac:3,April:4,Total:5";

and then use print_r().Then try use for loops....test it!is really fun!haha

 N/NOTE:try it!

2 comments:

  1. ermm.. i want to know how to rearrange the text after we explode it.
    for example, I explode a date (19-Feb-2011),then I want to rearrange it so that it can be saved in the database with its format.
    tq..
    ^-^

    ReplyDelete
  2. how about you use implode() function.for example: $date=implode(",",$date)..for more,read my latest post. tq

    ReplyDelete