【问题标题】:PHP undefined chars ? in output [closed]PHP未定义字符?在输出中[关闭]
【发布时间】:2013-05-23 16:02:18
【问题描述】:

我的问题是我不知道我的输出中的那些字符是从哪里来的,谁能解释我为什么在我的字符串中是这些字符以及我该怎么做才能取消它们?

该函数用于将'ä'、'ö'、'ü'变为'ae'、'oe'、'ue'

<?php

// str      | string argument
// needle   | searched char
// val      | value
// pos      | default 0 at start at offset zero 
// pos      | momently just working with default offset
function changeLetter($str, $needle, $val, $pos = 0) {
    $mstr = "";
    while (isset($str[$pos])) {            
        if (ord($str[$pos]) == ord($needle)) {
            $mstr .= $val;
            $pos++;
        } else {
            $mstr .= $str[$pos];
            $pos++;
        }
    }
    return $mstr;
}

echo changeLetter("täp@tecmax.com", 'ä', 'ae') . '<br>';
echo changeLetter("tüp@tecmax.com", 'ü', 'ue') . '<br>';
echo changeLetter("töp@tecmax.com", 'ö', 'oe') . '<br>';


//echo changeLetter("täp@tecmax.com", 'ä', 'ae', 3) . '<br>';   
?>

输出:

tae�p@tecmax.com

tue�p@tecmax.com

toe�p@tecmax.com

【问题讨论】:

标签: php string ascii


【解决方案1】:

你可以这样做:

echo changeLetter("täp@tecmax.com", 'ä', 'ae'), PHP_EOL;
echo changeLetter("tüp@tecmax.com", 'ü', 'ue'), PHP_EOL;
echo changeLetter("töp@tecmax.com", 'ö', 'oe'), PHP_EOL;

输出

taep@tecmax.com
tuep@tecmax.com
toep@tecmax.com

使用的功能

function changeLetter($str, $needle, $val, $pos = 0) {
    $next = function ($str, &$pos) {
        if (! isset($str[$pos]))
            return false;
        $char = ord($str[$pos]);
        if ($char < 128) {
            return $str[$pos ++];
        } else {
            if ($char < 224) {
                $bytes = 2;
            } elseif ($char < 240) {
                $bytes = 3;
            } elseif ($char < 248) {
                $bytes = 4;
            } elseif ($char = 252) {
                $bytes = 5;
            } else {
                $bytes = 6;
            }
            $str = substr($str, $pos, $bytes);
            $pos += $bytes;
            return $str;
        }
    };
    $mstr = "";
    while(($chr = $next($str, $pos)) !== false) {
        $mstr .= $chr == $needle ? $val : $chr;
    }
    return $mstr;
}

【讨论】:

    【解决方案2】:

    您需要更改文件编码,或使用&amp;auml;&amp;uuml;&amp;ouml; 而不是äüö

    【讨论】:

    • 不在 HTML 上下文中时不要使用 HTML 实体!很幸运,我今天的票都用完了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    相关资源
    最近更新 更多