6-07 1,360 views
参考:https://www.php.net/manual/en/function.str-split.php
最近碰到一个问题,客户的英文地址太长,超出接口api字段长度,所以需要解析下语句分解发送。
例子:
$str = "Zaharna Fabrika Kukush 1 building 69 entrance B floor 3 apartment 312";
p(str_split_word_aware($str,32));die;
结果:
<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>Array
(
[0] => Zaharna Fabrika Kukush 1
[1] => building 69 entrance B floor 3
[2] => apartment 312
)
</pre>
函数
function str_split_word_aware(string $string, int $maxLengthOfLine): array
{
if ($maxLengthOfLine <= 0) {
throw new RuntimeException(sprintf('The function %s() must have a max length of line at least greater than one', __FUNCTION__));
}
$lines = [];
$words = explode(' ', $string);
$currentLine = '';
$lineAccumulator = '';
foreach ($words as $currentWord) {
$currentWordWithSpace = sprintf('%s ', $currentWord);
$lineAccumulator .= $currentWordWithSpace;
if (strlen($lineAccumulator) < $maxLengthOfLine) {
$currentLine = $lineAccumulator;
continue;
}
$lines[] = $currentLine;
// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace;
$lineAccumulator = $currentWordWithSpace;
}
if ($currentLine !== '') {
$lines[] = $currentLine;
}
return $lines;
}