【问题标题】:How to strip unicode chars (LEFT_TO_RIGHT_MARK) from a string in php如何从php中的字符串中去除unicode字符(LEFT_TO_RIGHT_MARK)
【发布时间】:2010-12-28 03:37:34
【问题描述】:

我正在尝试在将字符串编码为 JSON 之前从字符串中删除 LEFT-TO-RIGHT-MARK (\u200e) 和 RIGHT-TO-LEFT-MARK (\u200f)。以下似乎都不起作用:

$s = mb_ereg_replace("\u200e", '', $s);
$s = preg_replace("#\u200e#u", '', $s);
$s = preg_replace("#\u200e#", '', $s);

感谢任何帮助!

【问题讨论】:

  • 字符串在哪个编码中?

标签: php regex utf-8


【解决方案1】:

这个问题折腾了几天,终于找到答案了!

$str = preg_replace('/(\x{200e}|\x{200f})/u', '', $str);

【讨论】:

  • 在@tmont 的回答(更高票数)没有为我工作的地方为我工作
【解决方案2】:

试试这个

preg_replace('/\x{E2}\x{80}\x{8E}/', '', $s); 
// strip unicode chars (LEFT_TO_RIGHT_MARK) 

【讨论】:

    【解决方案3】:

    您的 Unicode 转义错误,应该可以:

    preg_replace('/\x20(\x0e|\x0f)/', '', $string)
    

    测试:

    <?php
      $string = chr(0x20) . chr(0x0e) . 'fo' . chr(0x20) . chr(0x0e) . 'o' . chr(0x20) . chr(0x0f);
      echo $string . "\n";
      echo preg_replace('/\x20(\x0e|\x0f)/', '', $string);
    ?>
    

    或者,使用str_replace()

      str_replace(array("\x20\x0e", "\x20\x0f"), '', $string);
    

    【讨论】:

    • 实际上,它确实有效。我的测试是错误的。更新的答案包括 str_replace()。可能也可以使用 strtr()。
    • \x0e 到底是什么?
    • @iankit \x0echr(0x20) 的正则表达式等价
    【解决方案4】:

    你能试试这个吗?其utf8编码为200e和200f

    $s=preg_replace('/\xe2\x80[\x8e\x8f]/', '', $s)
    

    或使用 str_replace

    $s=str_replace("\xe2\x80\x8e", "", $s);
    $s=str_replace("\xe2\x80\x8f", "", $s);
    

    【讨论】:

      【解决方案5】:

      如何使用str_replace,并使用它的字符代码对该字符进行编码;可能是这样的:

      $new_string = str_replace("\x20\x0f", "", $your_string);
      

      而且,在您的情况下,由于您有几个不同的字符要替换,您可能会在一次调用 str_replace 时将它们全部替换:

      $new_string = str_replace(
          array(
              "\x20\x0e", 
              "\x20\x0f", 
          ),
          array(
              "", 
              "", 
          ),
          $your_string
      );
      

      它对你的问题有用吗?

      【讨论】:

        【解决方案6】:

        您是否尝试过以 UTF-8 对脚本文件进行编码,并在其中实际键入(或复制+粘贴)字符?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多