public function AbstractStringWrapper::wordWrap in Zircon Profile 8.0
Same name and namespace in other branches
- 8 vendor/zendframework/zend-stdlib/src/StringWrapper/AbstractStringWrapper.php \Zend\Stdlib\StringWrapper\AbstractStringWrapper::wordWrap()
Wraps a string to a given number of characters
Parameters
string $string:
int $width:
string $break:
bool $cut:
Return value
string|false
Overrides StringWrapperInterface::wordWrap
File
- vendor/
zendframework/ zend-stdlib/ src/ StringWrapper/ AbstractStringWrapper.php, line 147
Class
Namespace
Zend\Stdlib\StringWrapperCode
public function wordWrap($string, $width = 75, $break = "\n", $cut = false) {
$string = (string) $string;
if ($string === '') {
return '';
}
$break = (string) $break;
if ($break === '') {
throw new Exception\InvalidArgumentException('Break string cannot be empty');
}
$width = (int) $width;
if ($width === 0 && $cut) {
throw new Exception\InvalidArgumentException('Cannot force cut when width is zero');
}
if (StringUtils::isSingleByteEncoding($this
->getEncoding())) {
return wordwrap($string, $width, $break, $cut);
}
$stringWidth = $this
->strlen($string);
$breakWidth = $this
->strlen($break);
$result = '';
$lastStart = $lastSpace = 0;
for ($current = 0; $current < $stringWidth; $current++) {
$char = $this
->substr($string, $current, 1);
$possibleBreak = $char;
if ($breakWidth !== 1) {
$possibleBreak = $this
->substr($string, $current, $breakWidth);
}
if ($possibleBreak === $break) {
$result .= $this
->substr($string, $lastStart, $current - $lastStart + $breakWidth);
$current += $breakWidth - 1;
$lastStart = $lastSpace = $current + 1;
continue;
}
if ($char === ' ') {
if ($current - $lastStart >= $width) {
$result .= $this
->substr($string, $lastStart, $current - $lastStart) . $break;
$lastStart = $current + 1;
}
$lastSpace = $current;
continue;
}
if ($current - $lastStart >= $width && $cut && $lastStart >= $lastSpace) {
$result .= $this
->substr($string, $lastStart, $current - $lastStart) . $break;
$lastStart = $lastSpace = $current;
continue;
}
if ($current - $lastStart >= $width && $lastStart < $lastSpace) {
$result .= $this
->substr($string, $lastStart, $lastSpace - $lastStart) . $break;
$lastStart = $lastSpace = $lastSpace + 1;
continue;
}
}
if ($lastStart !== $current) {
$result .= $this
->substr($string, $lastStart, $current - $lastStart);
}
return $result;
}