[英]PHP trim unexpected behaviour
我在PHP中使用以下函數來修剪一些不需要的字符。
$inputString = "आनन्द मठ";
trim(html_entity_decode($inputString), " \t\n\r\0\x0B\xC2\xA0");
上面的代碼在所有情況下都可以正常工作,但在一個輸入字符串( आनन्द मठ
)中,它將其轉換為आनन्द म
。 它有不需要的。 परेटो- श्रेष्ठ
轉換為परेटो- श्रेष्
。
trim()
此功能使用iso-8859編碼。
您必須使用UTF8(Unicode)函數。 試試這個功能
function mb_trim($string, $charlist='\\\\s', $ltrim=true, $rtrim=true)
{
$both_ends = $ltrim && $rtrim;
$char_class_inner = preg_replace(
array( '/[\^\-\]\\\]/S', '/\\\{4}/S' ),
array( '\\\\\\0', '\\' ),
$charlist
);
$work_horse = '[' . $char_class_inner . ']+';
$ltrim && $left_pattern = '^' . $work_horse;
$rtrim && $right_pattern = $work_horse . '$';
if($both_ends)
{
$pattern_middle = $left_pattern . '|' . $right_pattern;
}
elseif($ltrim)
{
$pattern_middle = $left_pattern;
}
else
{
$pattern_middle = $right_pattern;
}
return preg_replace("/$pattern_middle/usSD", '', $string) );
}
在您的php中添加http標頭
header("Content-Type: text/html; charset=ISO-8859-1");
或將編碼放入meta標簽中:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.