【问题标题】:How to replace garbled characters in a string?如何替换字符串中的乱码?
【发布时间】:2011-09-21 22:36:51
【问题描述】:

我有这段文字...

“我并不是要让人信服,”大卫笑着承认道,“

...我想删除那些有趣的字符,我试过str_replace()但它不起作用。

有什么想法吗?

【问题讨论】:

  • 我很确定你应该解决一个潜在的问题。

标签: php char utf


【解决方案1】:

您可能处理的文本编码与其源编码不同。

因此,如果文本是 UTF-8,则您当前不会将其作为 UTF-8 处理。最简单的方法是发送一个标头,例如...

header('Content-Type: text/html; charset=UTF-8');

您也可以添加 meta 元素,但请确保它是您的 head 元素的第一个子元素。

您需要从源头上修复它,而不是稍后尝试修补它(这将永远无法正常工作)。

【讨论】:

  • 不也是显示页面的content-type吗?
  • @JaredFarrish:那会以不同的编码处理文本:)
  • 我不明白您的评论...从 Word 文件复制/粘贴时,我遇到了与 OP 相同的问题,并通过更改为 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 来修复它们(通常)。
  • @JaredFarrish:这将改变从处理一种文本编码作为另一种处理文本编码与正确的编码。这就是我试图在答案中说的。
  • 噢噢噢。好吧,这是有道理的。但也许你的答案可能更具体?
【解决方案2】:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
...
</head> 

不同的来源通常具有不同的编码,因此您需要指定呈现视图的编码。 utf-8 是最流行的,因为它涵盖了所有 ASCII 和许多其他语言。

php 的 utf8_(de)encode 将 iso-8859-1 转换为 utf-8,而相反的常规字符串操作函数不是多字节(utf-8 可以是)字符感知的。您要么使用特定于 mb_strings 的函数,要么使用某些参数启用编码。

//如果我记错了评论

【讨论】:

  • 您应该考虑描述为什么此代码会有所帮助。是的,它可能会解决问题,但问题的措辞使他们不知道他们需要此修复;解释他们为什么这样做。
【解决方案3】:

好吧,您使用的是可能应该使用的不同字符编码(您应该使用 utf-8 编码),所以我会更改它而不是尝试通过快速修复在现场修复它(您这样总体上会遇到更少的问题)。


如果你真的想用 PHP 修复它,你可以使用 ctype_alpha() 函数;你应该可以做这样的事情:

$theString = "your text here"; // your input string

$newString = ""; // your new string
$i = 0;
while($theString[$i]) // while there are still characters in the string
{
    if(ctype_alpha($theString[$i]) // if it's a character in your current set
    { 
       $newString .= $theString[$i]; // add it to the new string, increment pointer, and go to next loop iteration
       $i++;
       continue; 
    } // if the specific character at the $i index is an alphabetical character, add it to the new string
    else
    {
       $i++;
    } // if it's a bad character, just move the pointer up by one for the next iteration
}

然后根据需要使用 $newString。真的,只是改变你的字符编码而不是这样做。您希望整个项目的编码都相同。

【讨论】:

    猜你喜欢
    • 2014-12-03
    • 2022-01-03
    • 2023-04-09
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多