【问题标题】:How to remove backslash at end of string? [duplicate]如何删除字符串末尾的反斜杠? [复制]
【发布时间】:2021-02-11 02:55:52
【问题描述】:

我正在通过 node.js 中的 Discord 公会名称列表循环以生成包含以下格式数组的 php 文件

<?php

$guildLookup = array( "164930842483761" => "guildName1",
"56334196291325" => "guildName2",
);

?>

其中一个公会名称如下

/ ???? text ???? \

所以当我将它插入 php 数组时,它看起来像

<?php

$guildLookup = array( "164930842483761" => "guildName1",
"56334196291325" => "guildName2",
"56334196291342" => "/    ???? text ????   \",
"56334196291135" => "guildName4",
);

?>

在尝试访问 php 数组时会产生以下错误。

PHP Parse error: syntax error, unexpected '487648187306475542' (T_LNUMBER), expecting ')'

大概是因为反斜杠转义了行尾的 "。

我在 node.js 中尝试了以下几种变体来逃避公会名称末尾的反斜杠,甚至在将其放入 php 文件之前将其删除,但似乎无法使其正常工作。感谢我可以尝试的任何建议。

var newString = orginalString.replace(/\\$/, '\\');

【问题讨论】:

  • 转义你的斜线
  • @anubhava 包含数组的 php 文件在节点中创建并写入服务器。我认为该错误会阻止文件加载,所以我不明白如何使用 preg_quote?
  • @RisingSun 我试过了,但似乎找不到正确的正则表达式。
  • 这能回答你的问题吗? What does it mean to escape a string?

标签: javascript php regex


【解决方案1】:

'\\'表示\,必须用4个\\\\替换,也就是两个转义的\

//Use 4 backslashes for \\
//Also remove the $ because escaped characters can be anywhere
var newString = orginalString.replace(/\\/, '\\\\');

另外,我建议您验证报价。

var newString = orginalString.replace(/'/, "\\'");

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2017-05-10
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多