Skip navigation.

Contridentuallity

Not a fact, a theory!?

Posts tagged with "functions"

php explode

, , , ...

I was first introduced to this amazing function when I was building a keyword database for a product website. I needed to allow an administrator to create a range of keywords for a product in a comma/comma-space delimited format using a text input field. So the comma/comma-space delimited keyword string will be saved into a database in that format, but I needed a way to break up the string into all the seperate keywords if needed.

This was quite some time ago, and I didn't really have a large amount of knowledge on php, so after a bit of research on sites found by google for my search, I managed to find, grasp and understand the php explode function. It's a really simple function, but yet extremely useful in almost any application with or without a database.

Have a look at the sample below :

Let's say that we have a string of keywords in a database which is comma/comma-space delimited which looks something like this :

keyword1, keyword2, keyword3, keyword4, keyword5, keyword6


So the string you see above was inserted by the user, using an input text field. A form was submitted, and the string was stored into a database just as you see it there, possibly with the spaces as
 
using str_replace. In order to break this single string up into it's seperate keywords, and possiblly output those keywords, you would use a simple php explode function like the below :

<?php

//first insert the string into a variable
$string = "keyword1, keyword2, keyword3, keyword4, keyword5, keyword6";

//execute the explode function
$str = exlode(", ", $string);

//output the keywords one by one using foreach
foreach ($str as $s)
{
echo
"
$s <br/>
";
};

?>


So that's about it. The result of the code you see above will output something like this :

keyword1
keyword2
keyword3
keyword4
keyword5
keyword6


A simple, but yet extremely useful function of php which I use regularly due to the functionality it offers.
Download Opera, the fastest and most secure browser
December 2009
S M T W T F S
November 2009January 2010
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31