PHP 中使用 HTML 编号实体计算字符串长度

发布于 2024-12-23 13:20:18 字数 415 浏览 3 评论 0原文

我想用PHP计算字符串的长度。该字符串包含 HTML 实体编号,这会增加计算的字符数:破折号是 –,当我只想将其计为 1 时,它会计为 7。

我该如何做将html编号实体转换为特殊字符仅计算长度为1的形式?

示例字符串:

Goth-Trad – ‘Cosmos’

代码:

$string = html_entity_decode('Goth-Trad – ‘Cosmos’');
    echo strlen($string);

当我查找“20”时,会生成“38”。出了什么问题?

I would like to count the length of a string with PHP. The string contains HTML entity numbers, which inflate the number of characters that are counted: a dash is which is counted as 7 when I only want it to count as 1.

How do I convert the html numbered entities to a form where special characters are only counted with a length of 1?

Example string:

Goth-Trad – ‘Cosmos’

The code:

$string = html_entity_decode('Goth-Trad – ‘Cosmos’');
    echo strlen($string);

produces '38', when I'm looking for '20'. What is going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不爱素颜 2024-12-30 13:20:18

你可以使用这个:

$html = 'Goth-Trad – ‘Cosmos’';
echo strlen(utf8_decode(html_entity_decode($html, ENT_COMPAT, 'utf-8')));

You can use this:

$html = 'Goth-Trad – ‘Cosmos’';
echo strlen(utf8_decode(html_entity_decode($html, ENT_COMPAT, 'utf-8')));
夕嗳→ 2024-12-30 13:20:18

就解码一下然后数解码的个数?

$string = html_entity_decode("Goth-Trad – ‘Cosmos’",ENT_QUOTES,"UTF-8");
echo strlen($string);

Just decode it and count the decoded one?

$string = html_entity_decode("Goth-Trad – ‘Cosmos’",ENT_QUOTES,"UTF-8");
echo strlen($string);
任性一次 2024-12-30 13:20:18

请尝试使用以下编码函数:

<?php   

$string='Goth-Trad – ‘Cosmos’'; 

echo html_entity_text_length($string); // Calling the function 

//html_entity_text_length function start

function html_entity_text_length($string){
    preg_match_all("/&(.*)\;/U", $string, $pat_array);
    $additional=0;
    foreach ($pat_array[0] as $key => $value) {
       $additional += (strlen($value)-1);
    }

    $limit+=$additional;
    return  strlen($string)-$limit;
}

//html_entity_text_length function end

?>

Please Try with the following coding function:

<?php   

$string='Goth-Trad – ‘Cosmos’'; 

echo html_entity_text_length($string); // Calling the function 

//html_entity_text_length function start

function html_entity_text_length($string){
    preg_match_all("/&(.*)\;/U", $string, $pat_array);
    $additional=0;
    foreach ($pat_array[0] as $key => $value) {
       $additional += (strlen($value)-1);
    }

    $limit+=$additional;
    return  strlen($string)-$limit;
}

//html_entity_text_length function end

?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文