test123123
test123123

Reputation: 921

Echo new line in PHP

<?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?

Upvotes: 4

Views: 32471

Answers (5)

igorw
igorw

Reputation: 28239

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:

Upvotes: 0

Jan Zyka
Jan Zyka

Reputation: 17898

+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);

Upvotes: 4

etuardu
etuardu

Reputation: 5516

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.

Upvotes: 0

SW4
SW4

Reputation: 71150

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);

?>

Upvotes: 1

DhruvPathak
DhruvPathak

Reputation: 43235

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

Upvotes: 1

Related Questions