如何在 PHP 中拆分带有重音符号的字符串?

How can I split a string with accents in PHP?

我想拆分带有重音符号的 hurgarian 字符串。 现在我使用这个代码:

if(strlen($row['title'])<=20)
    {
        echo $row['title'];
    }
    else
    {
        echo substr($row['title'], 0, 17)." ...";
    }

我在数据库中使用 latin2_hungarian_ci 编码存储这些数据,并在 php 文件中使用字符集。在 PHP 和 HTML 部分:

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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

但是如果最后一个字符是非英语字符(é、á、ö、ü、ó、ő、ú、ű、í),则使用这种方式显示效果不佳。针对此字符出现一个 � 符号。 如果我不使用 substr,只需将整个标题写出来,一切都很好。

现在举个例子: Végzet erekly ... 或 Északi széless ...

我无法理解这个 substr,因为在我的示例中,其中一个写了 15 个字符和那个符号,另一个写了 16 个字符和那个符号。

如何写出所有字符的前 x 个字符?

使用iconv函数将字符集从latin2更改为utf-8,然后制作mb_substr.

echo iconv("ISO-8859-2","UTF-8//TRANSLIT", $string);

现在我尝试使用此代码:

function charfunction($myStr,$limit=17) {    
    $result = "";
    for($i=0; $i<$limit; $i++) {
        $result .= $myStr[$i];
    }
    return $result;    
}

并写出:

echo charfunction($row['title'])." ...";

$row['title'] 中的完整标题是 A végzet ereklyéi - Csontváros

如果我使用 $limit=17 它会写 A végzet erekly...

如果我更改为 $limit=18,它会显示 A végzet ereklyé ...

计算两个字符的 � 符号。但是 é 字符在它出现的那个位置。 为什么?

我是这样解决问题的:

if(strlen($row['title'])<=20)
    {
        echo $row['title'];
    }
    else
    {
        $result = "";
        $alphas = range('A', 'Z');
        $last = substr($row['title'], 15, 16);
        $title = $row['title'];
        if($alphas != "%".$last."%")
        {
            for($i=0; $i<18; $i++) {
                $result .= $title[$i];
            }

        }
        else
        {
            for($i=0; $i<17; $i++) {
                $result .= $title[$i];
            }
        }
        echo $result." ...";
    }

谢谢大家的帮助!