首页 > 解决方案 > 转换 PHP 字符串

问题描述

这是来自 REST 接口的响应负载:".my-test-class {\n\tbackground-color: blue;\n\tcolor: white;\n}"

我希望这是:

.my-test-class {
    background-color: blue;
    color: white;
}

没有双引号也没有转义字符..像这样的东西.. 只是普通的 CSS..我想在服务器端转换它

背后的方法是GET这样做的:

public function get_custom_css()
{
  $custom_css = wp_get_custom_css();

  $response = new WP_HTTP_Response($custom_css, 200, [
    "Content-Type" => "text/css; charset=UTF-8"
  ]);

  return rest_ensure_response($response);
}

由于第一个字符是点 ( ) $custom_css = trim($custom_css, '"');,所以去除双引号的做法无效。$custom_css[0] == '.'双引号似乎稍后应用。

我通过 Angular 收到这样的回复:

this.httpClient.get('http://my.domain.com/wordpress/?rest_route=/custom/css', {
  responseType: 'text'
})
  .subscribe((css: string): void => {
    const styleElement: HTMLStyleElement = document.createElement<'style'>('style');

    const textNode: Text = document.createTextNode(css);
    styleElement.appendChild(textNode);

    document.head.appendChild(styleElement);
  });

结果是这样的:

<style>".my-test-class {\n\tbackground-color: blue;\n\tcolor: white;\n}"</style>

这当然不是有效的 CSS,因此没有正确应用。

更新(2020-12-22)

正如@imvain2s 回答中所建议的那样,我决定省略换行符和制表符。我认为没有理由将它们保留在最终的 CSS 中。所以我现在使用它来删除转义序列:

$custom_css = preg_replace('/[\r\n\t]+/', '', $custom_css);

正如_sanitize_text_fields函数(链接)的第 5403 行中所做的那样

结果现在是:

<style>".my-test-class {background-color: blue;color: white;}"</style>

它仍然有这些双引号,我的猜测是 WordPress 在发送回响应时添加了它们。

我发现了其他有关“魔术引语”的文章和问题(请参阅此处),但我还不确定这些是否相关。

标签: phphtmlcssangularwordpress

解决方案


如果我正确理解了该功能,您应该能够在响应中应用 CSS。

此外,由于实际 CSS 中不需要新的行和制表符,我只是删除了它们的字符串版本。

    public function get_custom_css()
    {
      $custom_css = wp_get_custom_css();
    
      $response = new WP_HTTP_Response($custom_css, 200, [
        "Content-Type" => "text/css; charset=UTF-8"
      ]);
      
    $response = rest_ensure_response($response);
    
    $response = trim($response, '"');
    $response = str_replace("\\n","",$response);
    $response = str_replace("\\t","",$response);

/*
  or to keep the new lines and tabs
    $response = str_replace("\\n","\n",$response);
    $response = str_replace("\\t","\t",$response);
*/
    
      return $response;
    }

推荐阅读