_split_str_by_whitespace()
云策文档标注
概述
_split_str_by_whitespace() 是一个 WordPress 函数,用于将字符串按空白字符分割成块,每个块的长度尽可能接近指定目标长度,同时确保块包含其尾随分隔符。
关键要点
- 函数将输入字符串分割为数组块,每个块长度接近 $goal 参数指定的目标长度。
- 分割基于空白字符(如空格、制表符、换行符),块内不包含内部空白字符。
- 返回的块数组可以无损地通过空分隔符连接以重建原始字符串。
- 输入字符串不能包含空字符,或输出块的处理必须忽略空字符。
代码示例
_split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
array (
0 => '1234 67890 ', // 11 characters: Perfect split.
1 => '1234 ', // 5 characters: '1234 67890a' was too long.
2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long.
3 => '1234 890 ', // 11 characters: Perfect split.
4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long.
5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split.
6 => ' 45678 ', // 11 characters: Perfect split.
7 => '1 3 5 7 90 ', // 11 characters: End of $text.
);注意事项
- 函数从 WordPress 3.4.0 版本引入,主要用于 make_clickable() 等函数中处理文本格式化。
- 参数 $text 必须是字符串,$goal 必须是整数,分别表示要分割的字符串和期望的块长度。
- 返回值为数字索引数组,包含分割后的字符串块。
原文内容
Breaks a string into chunks by splitting at whitespace characters.
Description
The length of each returned chunk is as close to the specified length goal as possible, with the caveat that each chunk includes its trailing delimiter.
Chunks longer than the goal are guaranteed to not have any inner whitespace.
Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
_split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
array (
0 => '1234 67890 ', // 11 characters: Perfect split.
1 => '1234 ', // 5 characters: '1234 67890a' was too long.
2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long.
3 => '1234 890 ', // 11 characters: Perfect split.
4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long.
5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split.
6 => ' 45678 ', // 11 characters: Perfect split.
7 => '1 3 5 7 90 ', // 11 characters: End of $text.
);
Parameters
$textstringrequired-
The string to split.
$goalintrequired-
The desired chunk length.
Source
function _split_str_by_whitespace( $text, $goal ) {
$chunks = array();
$string_nullspace = strtr( $text, "rntvf ", "000000000000" );
while ( $goal < strlen( $string_nullspace ) ) {
$pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "00" );
if ( false === $pos ) {
$pos = strpos( $string_nullspace, "00", $goal + 1 );
if ( false === $pos ) {
break;
}
}
$chunks[] = substr( $text, 0, $pos + 1 );
$text = substr( $text, $pos + 1 );
$string_nullspace = substr( $string_nullspace, $pos + 1 );
}
if ( $text ) {
$chunks[] = $text;
}
return $chunks;
}
Changelog
| Version | Description |
|---|---|
| 3.4.0 | Introduced. |