Symfony: escape single quote string from database?
I need to generate a link with a Javascript confirmation dialog using Symfony's link_to()
method. The confirmation dialog text gets some of it's content from a database entry:
<?php echo link_to( "click here", 'category/delete?id='.$id, array( 'confirm' => 'Are you sure you want to delete the cate开发者_C百科gory: '.$category->getName().'?' ) ) ?>
But if the database entry has a single quote
in it, the confirm dialog doesn't work because the generated JS is surrounded with single quotes. So if I have a category called "John's Articles", the generated JS starts like this:
<a onclick="if (confirm('Are you sure you want to delete the category: John's Articles?')) { var f = document.createElement('form'); f.styl.... etc... "
So, the single quote in there screws up the confirmation, etc...
Anyways I thought I would simply run $category->getName()
through addslashes()
but it didn't add any slashes... I also tried saving out the category name as a separate variable ahead of time and adding slashes to that. But it didn't add any. Then I started looking at Symfony's escaping methods and found methods like esc_entities()
but they resulted in the text looking like John&#039;s Articles
.
What do I do? All I want to do is add in a single slash before single quotes in that string. I never tried str_replace("'","\'",$category->getName())
but THAT didn't even do anything. I can create my own basic string in my template like Alex's Test
and addslashes()
to it just fine. It's just this value from the database that I can't add any slashes to.
When I look at the value in the database, it looks just like John's Articles
. There are no special characters or encoded characters.
What am I missing here?
UPDATE
I've tried the following code with the following results:
echo $category->getName()."<br/>";
echo addslashes($category->getName())."<br/>";
$tmp = $category->getName();
echo addslashes($tmp)."<br/>";
$tmp = addslashes($category->getName());
echo $tmp."<br/>";
$tmp = "Testing's the Testing";
echo addslashes($tmp)."<br/>";
$tmp = str_replace("'","\\'",$category->getName());
echo $tmp;
Results:
John's Articles John's Articles John's Articles John's Articles Testing\'s the Testing John's Articles
The values from the database simply will not get slashes added to them...
Seems like you just use
addslashes($category->getName())
But you need assign returned value to other variable, ex.
$nameWithSlashes=addslashes($category->getName())
use json_encode() when inserting into Javascript. It's specifically intended to turn arbitrary data structures into syntactically valid Javascript.
<?php echo link_to( ....snip snip... category: '. json_encode($category->getName()) .'?' ) ) ?>
^^^^^^^^^^^^ ^
will take care of the problem, without any "risky" regexes/string replacements.
精彩评论