4
<?php
    include 'db_connect.php';
    $q = mysql_real_escape_string($_GET['q']);
    $arr = explode('+', $q);

    foreach($arr as $ing)
    {
        echo $ing;
        echo "<br/>";
    }
    mysql_close($db);
?>

Calling:

findByIncredients.php?q=Hans+Wurst+Wurstel

Source code HTML:

Hans Wurst Wurstel<br/>

Why is there only one newline?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
test123123
  • 911
  • 3
  • 16
  • 33

5 Answers5

4

+s in URL are urlencoded spaces. So what php sees in the variable is "Hans Wurst Wurstel". You need to split by space ' ', not +

arr = explode (' ',$q);
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
1

"+" gets converted to SPACE on URL decoding. You may want to pass your string as str1-str2-str3 in get parameter.

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
1

Try:

<?php
include 'db_connect.php';
$q = mysql_real_escape_string($_GET['q']);
$arr = explode (' ',$q);

foreach($arr as $ing)
{
echo $ing;
echo "<br/>";
}

mysql_close($db);

?>
SW4
  • 69,876
  • 20
  • 132
  • 137
0

Hans+Wurst+Wurstel is the url escaped query string. The php page will likely process it once unescaped (in this case, all +s will be translated into spaces). You should choose a delimiter for explode according to the string as it is in that moment. You can use print_r() for a raw print if you don't know how the string (or any kind of variable) looks like.

etuardu
  • 5,066
  • 3
  • 46
  • 58
0

Easy. While the standard RFC 3986 url encoding would encode the space " " as "%20", due to historical reasons, it can also be encoded as "+". When PHP parses the query string, it will convert the "+" character to a space.

This is also illustrated by the existence of both:

  • urlencode: equivalent of what PHP uses internally, will convert " " to "+".
  • rawurlencode: RFC-conformant encoder, will convert " " to "%20".

I'm assuming you want to explode by space. If you really wanted to encode a "+" character, you could use "%2B", which is the rawurlencode version and will always work.

(EDIT)

Related questions:

Community
  • 1
  • 1
igorw
  • 27,759
  • 5
  • 78
  • 90