问题
I have an associative array that is built dynamically from a MySQL table like so:
array(['p.id'] => 3, ['p.fname'] => 'Bill', ['p.lname'] => 'O\'Reilly')
This is a large array and was built this way for reasons that are too long to go into here. The problem, as you can see is that when we attempt to access the value of ['p.lname'] we get "O\"
Anyone have any ideas on how to get around this without modifying the way the array is built? I am currently stripping the slashes and internal apostrophes as a work around, but would prefer to leave the apostrophes in place and just strip the slashes.
This is complicated by the fact that the output goes into a form input like so:
$field = "<input type='text' name='$input_unique_id' style='width:$width;' value='$array_value' />";
回答1:
strip slashes
That's right so far.
This is complicated by the fact that the output goes into a form input
And this is a different issue: You use single quotes for the HTML element attributes, so you cannot use them in the attribute value like that*. Attribute values always should be escaped with htmlspecialchars (you will have to set the ENT_QUOTES
flag in this case)
*) your current HTML (with stripslashes
applied) looks like this:
<input value='O'Reilly'>
The Reilly'
part is invalid and thus ignored, this leaves value='O'
回答2:
You need to loop through each element of the array and strip the slashes as such:
foreach ($arr as $key => $value) {
$arr[$key] = stripslashes($value);
}
来源:https://stackoverflow.com/questions/14595040/an-escaped-apostrophe-in-associative-array-value