0

Little confusion in filtering " inverted commas for a javascript string in php.

$data = "I'am a string my name is "String".";
// problem is in following line.
$data = str_replace("\"","\\". "\"",$data);

$data = str_replace('<br />','\n',$data);
$data = str_replace("'","\\"."'",$data);

$row['story'] = $row['story'] . "<a href=\"#scroll\" onclick=\"addtext('$data'); return false\">Send</a>";

Update $data is some random string in a php page. I want to filter this string in simple text for a javascript function.e.g

 $data = "I'am a string my name is \"String\".";

I want to get the results like this.

onclick="addtext('I\'am a string my name is "String"'); return false"
user934820
  • 1,162
  • 3
  • 17
  • 48
  • And what is your problem here? Except poor syntax. – u_mulder Sep 18 '13 at 06:20
  • The code looks wierd. What are you planning to do? BTW I think theres a syntax issue in the first line. – Akshaya Shanbhogue Sep 18 '13 at 06:20
  • 1
    You forgot to escape a string in the first line. `$data = "I'am a string my name is \"String\".";` – JiminP Sep 18 '13 at 06:20
  • For a JavaScript string in PHP? What exactly do you mean? How are you getting the string? And, what ***exactly*** are you trying to do? I'm sorry, but your question doesn't make sense. – Amal Murali Sep 18 '13 at 06:21
  • onclick="addtext('') I want to get result here but when there is a double quote then there are lots of double quotes in result – user934820 Sep 18 '13 at 06:22
  • I added some more information. – user934820 Sep 18 '13 at 06:27
  • [see this question](http://stackoverflow.com/questions/18843010/need-to-ignore-if-there-is-any-single-quote-char-in-value-come-from-expression-l/18843281#18843281) – lastboy Sep 18 '13 at 06:27
  • 1
    Actually your onclick="addtext('I\'am a string my name is "String"'); return false" is not possible because this => " in "String" is the end of your addtext function – Wikunia Sep 18 '13 at 06:58
  • I done it by replacing it with some other character and later I replaced this other character to double quotes in upon calling java script – user934820 Sep 18 '13 at 13:59

1 Answers1

0

Why you make:

$data = str_replace("\"","\\". "\"",$data);

and not

$data = str_replace("'","\'",$data);

because your addtext function can't be working because a \ is missing in front of this => " "String" it must be \"String\"

I hope this is what you want to do.

And as a tip it's often easier to use

'...blablabla....<a href="la.html">la</a>' 

instead of

"....blablabla....<a href=\"la.html\">la</a>"
Wikunia
  • 1,564
  • 1
  • 16
  • 37