如何从PHP中删除所有换行符并从字符串中转义字符?

For a YouTube web-app I'm building in PHP, I have the simple video player, embedded with an <iframe>, and then a <div> with information about the currently loaded video (description, id, title, etc).

A <ul> contains a list of videos which are fetched using the PHP gData API from YouTube, and each <li> contains a link which activates JavaScript to change the video player to the correct video and also update the video info on the page.

Here's the issue: gData returns a multi-line, non-escaped sequence for the video description, which doesn't work in JavaScript. How should I remove line breaks and replace them with <br> (note that they aren't line breaks like , they are actual line breaks and newlines).

I also have to escape other things that won't work in a JavaScript string, such as the apostrophe character '. What is the best way to do this?

Marc B has given the best answer. Use json_encode: http://php.net/manual/en/function.json-encode.php Go, upvote his answer.

The following is my original response:

<?php
$data = "Hello, 'world'.
How are you doing?
\"Good?\"
";
$data = str_replace("
", '<br>', $data);
$data = str_replace('"', '\"', $data);
$data = str_replace("'", "\'", $data);
echo $data;
?>

The same stuff using regex:

<?php
$data = "Hello, 'world'.
How are you doing?
\"Good?\"
";
$data = preg_replace("/
/", '<br>', $data);
$data = preg_replace("/\"|'/", '\"', $data);
echo $data;
?>

Having given those examples, you don't really need to escape both single-quotes and double-quotes. In JavaScript, you can use double-quoted strings as well as single-quoted strings. So, use one and escape the other.

You might also want to escape backslash (replace \ with \\) to make sure that some funny YouTube uploader doesn't try to break your PHP script by placing a foo\'bar in the video description. Now, that can break your script if you don't escape backslash because the JavaScript string after replacements would now look like: 'foo\\'bar' which is a syntax error because the string finishes at 'foo\\'.

Don't bother trying to escape stuff yourself. Just use json_encode, which'll handle all those details for you:

<script type="text/javascript">
    var description = <?php echo json_encode($description) ?>;
</script>