ruslyrossi
ruslyrossi

Reputation: 366

How to keep string with quotes?

If user insert this data 16" HOUSEHOLD STAND FAN AA070021A the output should be same like this 16" HOUSEHOLD STAND FAN AA070021A but i only get this output 16\ HOUSEHOLD STAND FAN AA070021A, the quotes become "\" .

Before :

16\ HOUSEHOLD STAND FAN AA070021A

After :

16" HOUSEHOLD STAND FAN AA070021A

add_to_quote.php?product_name=16" HOUSEHOLD STAND FAN AA070021A

 <?php
  $product_name_1 = $_GET['product_name'];
  $product_name_2  = str_replace('"', "", $product_name_1);
  $product_name = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $product_name_2);
  echo $product_name;
  ?>

Upvotes: 0

Views: 438

Answers (4)

Tommy Nowicki
Tommy Nowicki

Reputation: 11

$product_name_1 = htmlentities($row["product_name"]);
$product_name_2  = str_replace('"', "", $product_name_1);
$product_name = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $product_name_2);

This solution worked for me.

Upvotes: 0

Aamer
Aamer

Reputation: 775

I have more than one comment about your code:

1- Sanitize you inputs. instead of:

$product_name_1 = $_GET['product_name'];

use:

$product_name_1 = mysql_real_escape_string(stripslashes($_GET['product_name']));

As for the quotes, one of the approaches I use and the easiest one so is to use base64_encode() method.

Here is an example (Which is taken from your code but the variables are treated differently):

add_to_quote.php?product_name=16" HOUSEHOLD STAND FAN AA070021A

 <?php
  $product_name_1 = $product_name_1 = htmlentities($_GET['product_name']);
  $product_name_2  = base64_encode($product_name_1);
  echo $product_name_2 . "<br />";
  $product_name_3 = base64_decode($product_name_2);
  echo $product_name_3;
  ?>

base64_encode() and base64_decode() are awesome functions in situations like this.

Upvotes: 2

flowfree
flowfree

Reputation: 16462

Add urlencode() to your link:

<a href="add_to_quote.php?product_name=<?php echo urlencode($product_name) ?>">Add To Quote</a>

Upvotes: 2

Nir Alfasi
Nir Alfasi

Reputation: 53525

Changing:

$product_name = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $product_name_2);

to:

$product_name = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $product_name_1);

worked for me.

Upvotes: 0

Related Questions