doudu2591 2011-10-03 19:05
浏览 52
已采纳

如何从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?

  • 写回答

2条回答 默认 最新

  • doucheng8471 2011-10-03 19:17
    关注

    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\\'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?