如何在PHP中的一定数量的字符后拆分字符串

Chr*_*rno 1 php string

我使用PHP返回用户的浏览器用户代理问题是我想要打印的地方:我不希望长度超过每行大约30个字符.有没有办法将返回的变量(从我调用的函数中获取字符串)分解为一定长度的子字符串?由于UA字符串的长度不同,我不确定会发生什么.

这是我返回用户代理的PHP代码:

function __toString() {
    return "Browser Name:
    return "Browser Name:             {$this->getBrowser()}  \n" .
           "    Browser Version:          {$this->getVersion()} \n" .
             "  Browser User Agent String:           {$this->getUserAgent()} \n" .
           "    Platform:                 {$this->getPlatform()} ";
}
Run Code Online (Sandbox Code Playgroud)

特别是这个电话$this->getUserAgent.我用这个输出:

<?php require_once('browser.php'); $browser =  new Browser(); echo $browser . "\n"; ?>
Run Code Online (Sandbox Code Playgroud)

现在,名称,版本和平台调用输出就像我想要的那样(因为在UA字符串中没有任何地方接近它们).

简而言之,如何拆分返回的用户字符串,使其每行不超过一定数量的字符?理想情况下,我想将它们存储到临时变量中,因为我必须在单词之间添加空格.例如,在它显示"平台"的地方,它前面有空格,因此它与浏览器版本垂直排列,然后是空格,以便从函数中返回的所有字符串的结果排成一行.

如果有人想在Github的代码上面看到我在做什么,函数调用在上线339-243,并且呼应结果去这个上线152.

在这一点上,我非常接近

只需要帮助在包装文本之前添加空格(请参阅下面的答案)

这就是我现在所拥有的:

$text1   = $this->getUserAgent();
$UAline1 = substr($text1, 0, 26);

$text2       = $this->getUserAgent();
$towrapUA    = str_replace($UAline1, '', $text2);
$wordwrapped = chunk_split($towrapUA, 26, "\n\r");
Run Code Online (Sandbox Code Playgroud)

在这一点上唯一的问题是如何在每个包装代码之前获得恒定数量的空格?我需要(比方说)在所有包装线之前的20个空格进行格式化.

Chr*_*wer 6

试试这个:

$str = chunk_split($string, 30, "\n\r");
// Splits a string after X chars (in this case 30) and adds a line break
Run Code Online (Sandbox Code Playgroud)

您也可以使用正则表达式尝试:

$str = preg_replace("/(.{30})/", "$1\n\r", $string);
Run Code Online (Sandbox Code Playgroud)

或者,正如上面的评论中所建议的,这也是一样的:

$str = wordwrap($string, 30, "<br />\n");
Run Code Online (Sandbox Code Playgroud)

更多信息:

http://php.net/manual/en/function.chunk-split.php

http://us2.php.net/wordwrap

编辑:

根据您编辑的问题,看起来这就是您要找的内容:

$text1    = $this->getUserAgent();
$UAline1  = substr($text1, 0, 26);
$towrapUA = str_replace($UAline1, '', $text1);

$space = str_repeat('&nbsp;', 20);

$wordwrapped = wordwrap($towrapUA, 26, "\n");
$wordwrapped = explode("\n", $wordwrapped); // Split at '\n'

$numlines = count($wordwrapped) - 1;
$string   = '';
$i = 0;

foreach($wordwrapped as $line) {
    if($i < $numlines) {
        $string .= $space . $line . "\n\r"; // Add \n\r back in if not last line
    } else {
        $string .= $space . $line; // If it's the last line, leave off \n\r
    }

    $i++;
}

echo $string;
Run Code Online (Sandbox Code Playgroud)