gpt4 book ai didi

处理奇怪字符时的php wordwrap cut参数

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:16 25 4
gpt4 key购买 nike

我在 php 中使用 wordwrap() 函数时遇到问题,例如中文字符。当 wordwrap 函数中的 $cut 参数设置为 true 时,它​​会通过插入问号来破坏字符串。

有解决办法吗?

最佳答案

native wordwrap函数对 unicode 使用不安全。这是一个 mb_wordwrap by Sam B. :

<?php
/**
* Multibyte capable wordwrap
*
* @param string $str
* @param int $width
* @param string $break
* @return string
*/
function mb_wordwrap($str, $width=74, $break="\r\n")
{
// Return short or empty strings untouched
if(empty($str) || mb_strlen($str, 'UTF-8') <= $width)
return $str;

$br_width = mb_strlen($break, 'UTF-8');
$str_width = mb_strlen($str, 'UTF-8');
$return = '';
$last_space = false;

for($i=0, $count=0; $i < $str_width; $i++, $count++)
{
// If we're at a break
if (mb_substr($str, $i, $br_width, 'UTF-8') == $break)
{
$count = 0;
$return .= mb_substr($str, $i, $br_width, 'UTF-8');
$i += $br_width - 1;
continue;
}

// Keep a track of the most recent possible break point
if(mb_substr($str, $i, 1, 'UTF-8') == " ")
{
$last_space = $i;
}

// It's time to wrap
if ($count > $width)
{
// There are no spaces to break on! Going to truncate :(
if(!$last_space)
{
$return .= $break;
$count = 0;
}
else
{
// Work out how far back the last space was
$drop = $i - $last_space;

// Cutting zero chars results in an empty string, so don't do that
if($drop > 0)
{
$return = mb_substr($return, 0, -$drop);
}

// Add a break
$return .= $break;

// Update pointers
$i = $last_space + ($br_width - 1);
$last_space = false;
$count = 0;
}
}

// Add character from the input string to the output
$return .= mb_substr($str, $i, 1, 'UTF-8');
}
return $return;
}
?>

关于处理奇怪字符时的php wordwrap cut参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6527880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com