如何在php中从字符串中去除unicode字符(LEFT_TO_RIGHT_MARK)

11

我想在将字符串编码为JSON之前从中删除左向右标记(\u200e)和右向左标记(\u200f)。以下两种方法似乎都无效:

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

感激不尽!


这个字符串使用的是哪种编码? - troelskn
6个回答

14

经过几天的探讨,我终于找到了答案!

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

对我来说有效,而@tmont的答案(得票更高)则没有。 - roryok

8

你的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()函数。 - tmont
\x0e是什么? - iankit
@iankit \x0echr(0x20) 的正则表达式等价形式。 - tmont

0

使用 str_replace 怎么样?并且通过字符编码来编写该字符;像这样:

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

而在你的情况下,由于你有几个不同的字符需要替换,你可以在一次调用str_replace中将它们全部替换:

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

这对你的问题有效吗?


0

试一下这个

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

0
你尝试过将脚本文件编码为UTF-8,并实际输入(或复制+粘贴)字符吗?

0
你能试一下吗?这是200e和200f的UTF-8编码。
$s=preg_replace('/\xe2\x80[\x8e\x8f]/', '', $s)

或者使用str_replace函数

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接