Search code examples
phpjavascripthtmlyoutubegdata-api

How do I remove all newlines and also escape characters from a string in 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 \n, 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?


Solution

  • 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'.\nHow are you doing?\n\"Good?\"\n";
    $data = str_replace("\n", '<br>', $data);
    $data = str_replace('"', '\"', $data);
    $data = str_replace("'", "\'", $data);
    echo $data;
    ?>
    

    The same stuff using regex:

    <?php
    $data = "Hello, 'world'.\nHow are you doing?\n\"Good?\"\n";
    $data = preg_replace("/\n/", '<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\\'.