2

I am attempting to echo a Tweet button in a table and have the tweet text from a json_array response.

The following code work unless the json response has a single quote(apostrophe) in it.

If the response has a single quote ( example I'm unhappy) this breaks the tweet text and stops after the I

is there away to strip all single quoyes from an array? or is there a better way to do what I am trying to accomplish?

    echo "<table border='0'>";
    echo "<tr><td><a href='https://twitter.com/share' class='twitter-share-button'{count} data-text='";
    echo $json_array["reasons"][0]["author_name"], "says ", $json_array["reasons"][0]["content"];
    echo " data-via='OnRecall' data-hashtags='OnRecall'>Tweet</a></td></tr>";
    echo "<tr><td>Name: </td><td>", $json_array["reasons"][0]["author_name"];
    echo " -> Liked: ", $json_array["reasons"][0]["like_count"], " times.</td></tr>";
    echo "<tr><td width= '20'></td><td>",  $json_array["reasons"][0]["content"];
    echo "</td></tr></table><p><hr></hr></p>";

So if $json_array["reasons"][0]["content"] has a single quote in it, the tweet text stops at it.

Thank you for reading.

1
  • What don't you understand? Commented Dec 24, 2015 at 19:21

2 Answers 2

1

You can use PHP's htmlspecialchars function to accomplish this. With the ENT_QUOTES flag, this function will encode all quotes as HTML entities (' becomes &#039;) and also significantly reduce your vulnerability to Cross-Site Scripting attacks -- this is especially important when the data you're displaying comes from an untrusted source (like someone else's Twitter feed):

$content = htmlspecialchars($json_array["reasons"][0]["author_name"], ENT_QUOTES)
    . "says "
     . htmlspecialchars($json_array["reasons"][0]["content"], ENT_QUOTES);
echo "<a ... data-text='$content'>';
Sign up to request clarification or add additional context in comments.

Comments

1

You need to escape all the single quotes in your string. You can use str_replace() function to replace all ' to \', like this:

$content = str_replace("'","\'",$json_array["reasons"][0]["content"]);
// now echo $content

Here's the reference:

1 Comment

Thank you, I tried this as well, but Twitter still didn't like the \' but your answer has helped me with a different issue I was having.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.