如何删除 PHP 字符串中的所有换行符和转义字符?
对于我用 PHP 构建的 YouTube Web 应用程序,我有一个简单的视频播放器,嵌入了 ,然后是一个
有关当前加载视频的信息(描述、ID、标题等)。
包含一个链接,可激活 JavaScript 以更改视频播放器到正确的视频并更新页面上的视频信息。
包含使用 PHP gData API 从 YouTube 获取的视频列表,每个
问题如下:gData
返回视频描述的多行非转义序列,这在 JavaScript 中不起作用。我应该如何删除换行符并将其替换为
(请注意,它们不是像 \n
这样的换行符,它们是实际的换行符和换行符)。
我还必须转义其他在 JavaScript 字符串中不起作用的内容,例如撇号字符 '
。最好的方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要费心去试图逃避自己的事情。只需使用 json_encode,它将为您处理所有这些详细信息:
Don't bother trying to escape stuff yourself. Just use json_encode, which'll handle all those details for you:
Marc B 给出了最佳答案。使用 json_encode: http://php.net/manual/en/function.json- encode.php 去吧,为他的答案投票。
以下是我的原始回复:
使用正则表达式的相同内容:
给出了这些示例后,您实际上不需要同时转义单引号和双引号。在 JavaScript 中,您可以使用双引号字符串和单引号字符串。因此,使用其中之一并逃避另一个。
您可能还想转义反斜杠(将
\
替换为\\
),以确保某些有趣的 YouTube 上传者不会尝试通过放置来破坏您的 PHP 脚本视频说明中的 >foo\'bar
。现在,如果您不转义反斜杠,则可能会破坏您的脚本,因为替换后的 JavaScript 字符串现在看起来像:'foo\\'bar'
这是一个语法错误,因为字符串以 <代码>'foo\\'。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:
The same stuff using regex:
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 afoo\'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\\'
.