Sameeksha Kumari
Sameeksha Kumari

Reputation: 1264

escape character not working as expected

I am trying to create html content in PHP and for onclick event I have included a function named uchat for a div. The function takes a name parameter which is a string.

Like below:

$name = "Php string";

$echostr .= "<div onClick='uchat(\'$name\')'>
             </div>";

But, passing a string value like this causes syntax error when div is clicked. Because, single quote is within a single quote. I have tried to escape it, but it still doesnt work.

The error is this:

SyntaxError: illegal character
uchat(\

I am not sure how to escape a string parameter and I have come across this problem so many times, Please help if you have a solution for this.

Thanks.

Upvotes: 2

Views: 267

Answers (4)

Matthieu Bilbille
Matthieu Bilbille

Reputation: 161

Here are 2 clean and simple ways to do this:

1. Classic concat

    $name = "Php string";
    $str = "<div onClick=\"uchat('" . $name . "')\"></div>";
    print $str;

2. Using sprintf (https://www.php.net/manual/en/function.sprintf.php)

    $name = "Php string2";
    $str = sprintf("<div onClick=\"uchat('%s')\"></div>", $name);
    print $str;

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 99071

This works:

<?php
$name = "Php string";

$echostr .= <<< EOF
<div onClick="uchat('$name')"></div>
EOF;

echo $echostr;
?>

Output:

<div onClick="uchat('Php string')"></div>

In order to avoid escaping all double quotes and to make the html code more readable you can use EOF.

See it action : http://ideone.com/vRCCVH

Upvotes: 1

revo
revo

Reputation: 48761

Escaped single quotes will conflict with outer ones:

$echostr .= "<div onClick=\"uchat('$name')\">
             </div>";

Upvotes: 2

PravinS
PravinS

Reputation: 2594

try like this

$echostr .= "<div onClick='uchat(&quot;$name&quot;)'></div>";

Upvotes: 1

Related Questions