我想在将字符串编码为JSON之前从中删除左向右标记(\u200e)和右向左标记(\u200f)。以下两种方法似乎都无效:
$s = mb_ereg_replace("\u200e", '', $s);
$s = preg_replace("#\u200e#u", '', $s);
$s = preg_replace("#\u200e#", '', $s);
感激不尽!
经过几天的探讨,我终于找到了答案!
$str = preg_replace('/(\x{200e}|\x{200f})/u', '', $str);
你的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);
\x0e
是 chr(0x20)
的正则表达式等价形式。 - tmont使用 str_replace
怎么样?并且通过字符编码来编写该字符;像这样:
$new_string = str_replace("\x20\x0f", "", $your_string);
而在你的情况下,由于你有几个不同的字符需要替换,你可以在一次调用str_replace
中将它们全部替换:
$new_string = str_replace(
array(
"\x20\x0e",
"\x20\x0f",
),
array(
"",
"",
),
$your_string
);
这对你的问题有效吗?
试一下这个
preg_replace('/\x{E2}\x{80}\x{8E}/', '', $s);
// strip unicode chars (LEFT_TO_RIGHT_MARK)
$s=preg_replace('/\xe2\x80[\x8e\x8f]/', '', $s)
或者使用str_replace函数
$s=str_replace("\xe2\x80\x8e", "", $s);
$s=str_replace("\xe2\x80\x8f", "", $s);