p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: Turning multiple words from input into an array


Message #1 by Jefferis Peterson <jefferis@p...> on Wed, 02 Oct 2002 15:43:40 -0400
I'm trying to figure out how to turn  multiple words from a text field input
form into an array for a query.

So far I know you've got to strip out the spaces

 $keywords = preg_replace("(\s+)", " ",   );

But I can't find a simple tutorial on  working with the results to turn the
items into an array.

Any ideas appreciated.

Jeff 

~~~~~~~~~~~~
Jefferis Peterson, Pres.
Web Design and Marketing
http://www.PetersonSales.net
Tel .  xxx-xxx-xxxx
ICQ 19112253

http://www.Slippery-Rock.com - 7,000 hits per year

Message #2 by "Nikolai Devereaux" <yomama@u...> on Wed, 2 Oct 2002 12:59:17 -0700
> I'm trying to figure out how to turn  multiple words from a text field input
> form into an array for a query.
>
> So far I know you've got to strip out the spaces
>
>  $keywords = preg_replace("(\s+)", " ",   );
>
> But I can't find a simple tutorial on  working with the results to turn the
> items into an array.

Try using preg_split() instead.  That splits a string using a regex pattern
instead of a fixed string (a la split() or explode()).

$keywords = preg_split('/\s+/', $form_input);

More info:
  http://www.php.net/preg_split

Notice that the first example on the page is almost exactly what you want to
do.

It might even be a good idea to include punctuation in the charset, so that a
search for "big, yellow diamonds." doesn't search for "big," and "diamonds."

$pattern = '/[\s,.]+/';
$keywords = preg_split($pattern, $form_input);


take care,

nik

Message #3 by Bernardo Zuniga <bzuniga@e...> on Wed, 2 Oct 2002 16:06:45 -0400
There are 2 functions for strings that doe this. One is explode() and 
the other is implode(). Tthe syntax is pretty easy - 
explode("delimiter", $string_name)
I believe you want to use explode, this takes a string and turns it 
into an array.
Instead of stripping all the spaces out, and assuming there is only one 
space per word, try this
$my_string = "Text from input field";
$my_array = explode(" ", $my_string);
if you check the contents of $my_array after, it should contain the 
words of your string.
On Wednesday, October 2, 2002, at 03:43 PM, Jefferis Peterson wrote:

> I'm trying to figure out how to turn  multiple words from a text field 
> input
> form into an array for a query.
>
> So far I know you've got to strip out the spaces
>
>  $keywords = preg_replace("(\s+)", " ",   );
>
> But I can't find a simple tutorial on  working with the results to 
> turn the
> items into an array.
>
> Any ideas appreciated.
>
> Jeff
>
> ~~~~~~~~~~~~
> Jefferis Peterson, Pres.
> Web Design and Marketing
> http://www.PetersonSales.net
> Tel .  xxx-xxx-xxxx
> ICQ 19112253
>
> http://www.Slippery-Rock.com - 7,000 hits per year
>
>
>

Message #4 by "Nikolai Devereaux" <yomama@u...> on Wed, 2 Oct 2002 13:16:40 -0700
> Instead of stripping all the spaces out, and assuming there is only one
> space per word, try this

The problem here is that you admit to making an assumption -- which is breaking
the most important rule of software engineering:

NEVER assume the user will give you well-formed input.

Most applications would be 1/3 their size and a LOT more elegant if they were
developed without all the validity checks.

Make this your mantra, print it out and tape it to your monitors:


        U S E R S   A R E   I D I O T S


If you tell them to enter a number between 1 and 10, you'll eventually have a
user submit "potato".  Guaranteed.

nik

Message #5 by Jefferis Peterson <jefferis@p...> on Wed, 02 Oct 2002 16:27:46 -0400
On 10/2/02 4:06 PM, "Bernardo Zuniga" <bzuniga@e...> wrote:

> space per word, try this
> $my_string = "Text from input field";
> $my_array = explode(" ", $my_string);
> if you check the contents of $my_array after, it should contain the
> words of your string.

Something doesn't work here:

<?php
echo $keysearch;
$pattern = '/[\s,.]+/';
 $my_array = explode($pattern, $keysearch);
 echo $my_array;
  ?>

If I input data froma field called $keysearch, all the words echo with the
first statement, but the next echo produces the word ARRAY not all the words
in the array.

~~~~~~~~~~~~
Jefferis Peterson, Pres.
Web Design and Marketing
http://www.PetersonSales.net
Tel .  xxx-xxx-xxxx
ICQ 19112253

http://www.Slippery-Rock.com - 7,000 hits per year

Message #6 by Bernardo Zuniga <bzuniga@e...> on Wed, 2 Oct 2002 16:35:51 -0400
That's a good point, but that doesn't answer the question that was 
presented by this post.
On Wednesday, October 2, 2002, at 04:16 PM, Nikolai Devereaux wrote:

>
>> Instead of stripping all the spaces out, and assuming there is only 
>> one
>> space per word, try this
>
> The problem here is that you admit to making an assumption -- which is 
> breaking
> the most important rule of software engineering:
>
> NEVER assume the user will give you well-formed input.
>
> Most applications would be 1/3 their size and a LOT more elegant if 
> they were
> developed without all the validity checks.
>
> Make this your mantra, print it out and tape it to your monitors:
>
>
>         U S E R S   A R E   I D I O T S
>
>
> If you tell them to enter a number between 1 and 10, you'll eventually 
> have a
> user submit "potato".  Guaranteed.
>
> nik
>
>
>

Message #7 by "Nikolai Devereaux" <yomama@u...> on Wed, 2 Oct 2002 13:40:14 -0700
> That's a good point, but that doesn't answer the question that was 
> presented by this post.

Touche!  I answered it in a separate reply. =)

Message #8 by Bernardo Zuniga <bzuniga@e...> on Wed, 2 Oct 2002 16:42:35 -0400
try this
foreach($my_array as $key => $value) {
	echo "$key: $value<br>";
}


On Wednesday, October 2, 2002, at 04:27 PM, Jefferis Peterson wrote:

> On 10/2/02 4:06 PM, "Bernardo Zuniga" <bzuniga@e...> wrote:
>
>> space per word, try this
>> $my_string = "Text from input field";
>> $my_array = explode(" ", $my_string);
>> if you check the contents of $my_array after, it should contain the
>> words of your string.
>
> Something doesn't work here:
>
> <?php
> echo $keysearch;
> $pattern = '/[\s,.]+/';
>  $my_array = explode($pattern, $keysearch);
>  echo $my_array;
>   ?>
>
> If I input data froma field called $keysearch, all the words echo with 
> the
> first statement, but the next echo produces the word ARRAY not all the 
> words
> in the array.
>
> ~~~~~~~~~~~~
> Jefferis Peterson, Pres.
> Web Design and Marketing
> http://www.PetersonSales.net
> Tel .  xxx-xxx-xxxx
> ICQ 19112253
>
> http://www.Slippery-Rock.com - 7,000 hits per year
>
>
>

Message #9 by "Nikolai Devereaux" <yomama@u...> on Wed, 2 Oct 2002 13:55:02 -0700
> Something doesn't work here:
>
> <?php
> echo $keysearch;
> $pattern = '/[\s,.]+/';
>  $my_array = explode($pattern, $keysearch);
>  echo $my_array;
>   ?>
>
> If I input data froma field called $keysearch, all the words echo with the
> first statement, but the next echo produces the word ARRAY not all the words
> in the array.


You're confusing explode() for preg_split().  explode() takes a string
delimiter, not a pattern.  You're saying that you want to split up your string
into tokens that are delimited by the string '/[\s,.]+/'.

one more thing, though -- I forgot to escape the '.' in the pattern.  '.' is a
special character that means "match anything", so we have to escape it with a
backslash to have it revert to just a decimal point.


Try this:

$pattern  = '/[\s,\?\.!]+/';
$my_array = preg_split($pattern, $keysearch);


Testing it on "hello, world!  how are you doing?  Great.  I\'m fine, too."

Yields the following $my_array:

Array
(
    [0] => hello
    [1] => world
    [2] => how
    [3] => are
    [4] => you
    [5] => doing
    [6] => Great
    [7] => I\'m
    [8] => fine
    [9] => too
    [10] =>
)


Notice that 10 is empty because preg_split() creates a token for what comes
after the last period and the end of the string.  This is the empty string, but
it's still an array index.


hth,

nik

Message #10 by "Nikolai Devereaux" <yomama@u...> on Wed, 2 Oct 2002 13:58:21 -0700
One more note:

>  echo $my_array;


That will always print "Array", because echo accepts a string argument.  PHP
has to convert any variables or constants of any other data type to strings
on-the-fly if they are passed to echo.

For example:

echo 5;  //  php converts the integer 5 to the string "5".

$myObj = new MyObject();
echo $myObj; // php converts the object $myObj to the string "Object".

$my_array = array();
echo $myArr;  // php converts the array $myArr to the string "Array"


take care,

nik

Message #11 by Jefferis Peterson <jefferis@p...> on Wed, 02 Oct 2002 17:31:59 -0400
Good !  echo's a funny character though:

 
0: yellow diamonds gold jewels


On 10/2/02 4:42 PM, "Bernardo Zuniga" <bzuniga@e...> wrote:

> try this
> foreach($my_array as $key => $value) {
> echo "$key: $value<br>";
> }
> 

~~~~~~~~~~~~
Jefferis Peterson, Pres.
Web Design and Marketing
http://www.PetersonSales.net
Tel .  xxx-xxx-xxxx
ICQ 19112253

http://www.Slippery-Rock.com - 7,000 hits per year

Message #12 by "Nikolai Devereaux" <yomama@u...> on Wed, 2 Oct 2002 14:45:53 -0700
That's exactly what you'd expect, though!

$my_array is an array.  Running it through print_r() will recursively dump it's
contents.  In that case, since you were using explode(), you would've had only
ONE item in the array; the original keyword string.

So when you use the foreach() loop to iterate across the array elements, you
get the index of the element stored in $key, and the value at that index stored
in $value.

$key is 0 for the first index, and $value, like I mentioned above, is the
original string.

echo "$key: $value<br>", then, does exactly what you'd expect -- it substitutes
0 for $key and your original keywords string for $value.


This must be the fourth or fifth time in the past week I've posted this really
handy function:

function printr($var, $desc = '')
{
   echo '<PRE>';
   if($desc != '')
   {
      echo $desc . ': ';
   }
   echo "</PRE>\n";
}


Example usage:

printr($my_array, '$my_array, after running preg_split()');


Take care,

nik

Message #13 by CathyV227@a... on Wed, 2 Oct 2002 23:07:21 EDT
john???????

Message #14 by CathyV227@a... on Wed, 2 Oct 2002 23:08:18 EDT
john?????????

Message #15 by CathyV227@a... on Wed, 2 Oct 2002 23:08:37 EDT
john

Message #16 by Jefferis Peterson <jefferis@p...> on Thu, 03 Oct 2002 09:02:30 -0400
Nik, can you explain this code to me?

$desc I assume is my description field?

I can't follow what this is doing.

Jeff


On 10/2/02 5:45 PM, "Nikolai Devereaux" <yomama@u...> wrote:

> This must be the fourth or fifth time in the past week I've posted this really
> handy function:
> 
> function printr($var, $desc = '')
> {
>  echo '<PRE>';
>  if($desc != '')
>  {
>     echo $desc . ': ';
>  }
>  echo "</PRE>\n";
> }
> 
> 
> Example usage:

~~~~~~~~~~~~
Jefferis Peterson, Pres.
Web Design and Marketing
http://www.PetersonSales.net
Tel .  xxx-xxx-xxxx
ICQ 19112253

http://www.Slippery-Rock.com - 7,000 hits per year

Message #17 by "Nikolai Devereaux" <yomama@u...> on Thu, 3 Oct 2002 10:54:02 -0700
> Nik, can you explain this code to me?
>
> $desc I assume is my description field?
>
> I can't follow what this is doing.


Sure thing.  First, read the docs for print_r()

  http://www.php.net/print_r


All my function does is wrap a call to print_r within <PRE></PRE> tags so that
the output looks better in an HTML page.

The $desc parameter is an optional parameter which offers you the ability to
describe what's being printed out.

So:

printr($my_array);  will output

Array
(
    [0] => big
    [1] => shiny
    [2] => yellow
    [3] => diamonds
)


printr($my_array, '$my_array, after running preg_split()');

will output:


$my_array, after running preg_split(): Array
(
    [0] => big
    [1] => shiny
    [2] => yellow
    [3] => diamonds
)



Note that you don't have to use this on arrays.  I use it all the time.
Additional realistic examples:

$query = "INSERT INTO users VALUES ($username, $password)";
printr($query, 'New user query');

$result = mysql_query($query);
printr($result, '$result after running ' . $query);


Hope this helps,

Nik


  Return to Index