Forum Moderators: coopster

Message Too Old, No Replies

Parsing a String in PHP

         

ramoneguru

2:29 am on Apr 15, 2005 (gmt 0)

10+ Year Member



I have a form varibale:
names = "john Adams, Mark J. Smith, david Crane"

now I have the POST data of this:
$_POST['names']

I want to take all those names (seperately, they'll be seperated by a comma) and store them in a mysql database. How would I go about doing this? I am just not sure about parsing....I can do the database part, but I just can't parse the string to get the names.

--Nick

ironik

2:37 am on Apr 15, 2005 (gmt 0)

10+ Year Member



If they are comma seperated try:


<?php
if (isset($_POST['names']))
{
$names = array(); // array to store each name
if (is_int(strpos(',', $_POST['names'])))
{
$names = explode(',', $_POST['names']); // Multiple names
} else {
$names[] = $_POST['names']; // Just one name
}
}
?>

That will see if $_POST['names'] exists, and if it contains a comma. If it does then it splits it into an array of names which you can then use to insert into your database.

Salsa

4:25 am on Apr 15, 2005 (gmt 0)

10+ Year Member



If the separator might include white space as well as commas (as in your example), you might also want to trim() the elements.

ramoneguru

4:31 am on Apr 15, 2005 (gmt 0)

10+ Year Member



Cool, thanks. I'll be sure to do the trim before I insert them.
--Nick