我需要一个能清理字符串特殊字符的函数。我 NOT 希望这个转换HTML字符
<br />
至
<br />
我希望将以下内容转换为:•,½,'到html代码。
这是我目前使用的功能,但它似乎不适用于分数..
function cleanText($str){
$str = str_replace("Ñ" ,"Ñ", $str);
$str = str_replace("ñ" ,"ñ", $str);
$str = str_replace("ñ" ,"ñ", $str);
$str = str_replace("Á","Á", $str);
$str = str_replace("á","á", $str);
$str = str_replace("É","É", $str);
$str = str_replace("é","é", $str);
$str = str_replace("ú","ú", $str);
$str = str_replace("ù","ù", $str);
$str = str_replace("Í","Í", $str);
$str = str_replace("í","í", $str);
$str = str_replace("Ó","Ó", $str);
$str = str_replace("ó","ó", $str);
$str = str_replace("“","“", $str);
$str = str_replace("”","”", $str);
$str = str_replace("‘","‘", $str);
$str = str_replace("’","’", $str);
$str = str_replace("—","—", $str);
$str = str_replace("–","–", $str);
$str = str_replace("™","™", $str);
$str = str_replace("ü","ü", $str);
$str = str_replace("Ü","Ü", $str);
$str = str_replace("Ê","Ê", $str);
$str = str_replace("ê","î", $str);
$str = str_replace("Ç","Ç", $str);
$str = str_replace("ç","ç", $str);
$str = str_replace("È","È", $str);
$str = str_replace("è","è", $str);
$str = str_replace("•","•" , $str);
$str = str_replace("¼","¼" , $str);
$str = str_replace("½","½" , $str);
$str = str_replace("¾","¾" , $str);
$str = str_replace("½","½" , $str);
return $str;
}
答案 0 :(得分:4)
您可以使用ENT_SUBSTITUTE
属性将htmlentities
替换为整个功能。除了正常工作外,它还会更快地执行。
注意: ENT_SUBSTITUTE
自PHP 5.4起可用。
答案 1 :(得分:2)
猜猜是时候看一下htmlentities
PHP函数及其选项了。
基本上,您可以用以下内容替换整个功能:
$str = htmlentities( $str );
它也会更有效率。
如果需要特殊处理(尤其是ENT_SUBSTITUTE
),请务必查看函数的可选参数。
$str = htmlentities( $str, ENT_SUBSTITUTE );
答案 2 :(得分:2)
试试这个,我用这个函数将任何东西/所有东西都转换为unicode:
class unicode_replace_entities {
public function UTF8entities($content="") {
$contents = $this->unicode_string_to_array($content);
$swap = "";
$iCount = count($contents);
for ($o=0;$o<$iCount;$o++) {
$contents[$o] = $this->unicode_entity_replace($contents[$o]);
$swap .= $contents[$o];
}
return mb_convert_encoding($swap, "UTF-8"); //not really necessary, but why not.
}
public function unicode_string_to_array( $string ) { //adjwilli
$strlen = mb_strlen($string);
while ($strlen) {
$array[] = mb_substr( $string, 0, 1, "UTF-8" );
$string = mb_substr( $string, 1, $strlen, "UTF-8" );
$strlen = mb_strlen( $string );
}
return $array;
}
public function unicode_entity_replace($c) { //m. perez
$h = ord($c{0});
if ($h <= 0x7F) {
return $c;
} else if ($h < 0xC2) {
return $c;
}
if ($h <= 0xDF) {
$h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
$h = "&#" . $h . ";";
return $h;
} else if ($h <= 0xEF) {
$h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
$h = "&#" . $h . ";";
return $h;
} else if ($h <= 0xF4) {
$h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
$h = "&#" . $h . ";";
return $h;
}
}
}
$oUnicodeReplace = new unicode_replace_entities();
$oUnicodeReplace->UTF8entities($string);
请注意,它将转换所有内容,但它会照顾奇怪的字符,否则......不是我自己的脚本,但我不知道我在哪里找到它。
答案 3 :(得分:1)