[英]How to replace ideographic space in PHP string?
表意空间是http://www.charbase.com/3000-unicode-ideographic-space ,它是一个 CJK 标点符号。 它看起来像一个普通的空间,但实际上它在屏幕上有 2 个位置而不是 1 个(就像汉字那样)
我尝试使用str_replace(" ","",$mystring)
来摆脱它们,但当然它不起作用,因为我在这里输入的空间是一个 ASCII 空间。 我也试过用汉字输入法手动输入表意空格,但这样看来我也会去掉部分其他字符的代码,返回乱码。
那么我怎样才能摆脱这些空间呢?
通过从链接到的信息页面复制符号,我能够很好地替换字符。 您可能希望为表意空间创建CONST
别名,以帮助更清楚地创建和查找/替换编码。
// contains ideographic space between words
$start = 'before after';
// contains ideographic space in needle parameter
$test1 = str_replace(' ', '_', $start);
// contains ideographic space
define('ID_SPACE', ' ');
$test2 = str_replace(ID_SPACE, '&', $start);
// contains normal space in needle parameter
$test3 = str_replace(' ','_',$start);
// make sure we are using utf8 for this test
header('Content-Type: text/html; charset=utf-8');
echo $start.'<br/>';
echo $test1.'<br/>';
echo $test2.'<br/>';
echo $test3;
输出:
before after
before_after
before&after
before after
编辑以回答问题
当您看不到它时,该字符显示在显示的框中,只需单击并拖动即可选择任何其他文本,然后您可以根据需要粘贴它。 您也可以从我的答案中复制包含空格的代码。 如果你看到像 
那么你需要将你的charset设置为utf-8
您可以直接从转义的数值转换内容。 我有以下功能坐了很多年。 我没有写它,我担心我不记得我发现它的位置。 这有点像黑客,但我认为这是一个有用的。
<?php
function code2utf($num) {
if($num<128)return chr($num);
if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128).chr(($num&63)+128);
return '';
}
print "a" . code2utf(0x3000) . "b" . code2utf(0x1f44d) . "\n";
当我跑这个时,我看到:
$ php -f utftest
a b👍
请注意,看起来像两个空格的是一个双宽字符。
也许您可以使用上面的函数来构造输入字符串,如下所示:
str_replace(code2utf(0x3000),"",$mystring);
像WebChemist的复制和粘贴解决方案这样的解决方案的明显优势在于它完全是程序化的,并且不需要任何特殊功能作为程序员工具的一部分。 在重新格式化代码时,您不会意外覆盖ID_SPACE字符,并且该函数可以重用于您可能需要表示的其他UTF8字符,而无需在代码中实际包含这些字符。
当然,另一种方法是使用内置的PHP函数html_entity_decode()
。 以下结果与我的函数相同,使用HTML转义字符作为输入:
$ php -r 'print html_entity_decode("a b👍") . "\n";'
a b👍
一种对我str_replace
的方法,将其原始编码为HTML实体和str_replace
返回正常的空白。
//The space we're looking out for
$ideoSpace = "%26%23x3000%3B";
$space = "%20";
//Search string (Notice the wider space)
$searchstr = "Please find me a Oil Filter";
//Begin conversion
$searchstr = rawurldecode( str_replace( $ideoSpace, $space, rawurlencode( $searchstr )));
//echos "Please find me a Oil Filter"
也许不是最优雅的解决方案。 然而不幸的是,搜索对我们没有用,因为implode()
无法为我们的日本客户分割字符串。
public function fixSpaceProblem($string) {
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
$hasBugString = (mb_split('[[:space:]]', $string));
$fixedString = join(" ",$hasBugString);
return $fixedString;
}
我自己使用它并且它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.