2011-03-31 45 views
2

我需要做一些包括使用爆炸来创建数组的函数。我看过几个例子,但最后我真的很困惑!有一个简单的可读方式吗? (//注释?)PHP> echo字符串,每行3个字符分隔?

就拿一段文字:

"This is a simple text I just created". 

输出应该是这样的:

This is a 
simple text I 
just created 

所以爆炸应该文本拆分成3行每个字。

+1

我想我们可能需要更多的澄清一下。你想要爆炸什么,你想用数组做什么? – 2011-03-31 18:54:51

+0

我不明白问题,你到底需要什么? – Faraona 2011-03-31 18:55:54

+0

对不起,拿一个文本>“这是我刚刚创建的一个简单的文本”。 输出应该是这样的: 这是我 就创建了一个 简单的文本 所以爆炸应该文本拆分成每3个字线。 – Gabriel 2011-03-31 18:56:07

回答

0

使用substr()功能link

例子:

<?php 
$rest = substr("abcdef", -1); // returns "f" 
$rest = substr("abcdef", -2); // returns "ef" 
$rest = substr("abcdef", -3, 1); // returns "d" 
?> 

你的情况:

<?php 
$rest = substr("This is a simple text I just created", 0, 15); //This will return first 15 characters from your string/text 

echo $rest; // This is a simpl 
?> 
+0

那么它应该是一个单一的回声,我可以使用substr()存档这个? – Gabriel 2011-03-31 19:02:26

+0

我不明白你的档案是什么意思? – Faraona 2011-03-31 19:03:53

+0

我现在告诉你如何。 – Faraona 2011-03-31 19:04:44

0

爆炸刚刚拆分在指定字符的字符串。没有什么更多。

explode(',','Text,goes,here');

这会在字符串遇到a时分割字符串,并返回一个数组。

用空格字符

爆炸(””, '文字放在这里')分裂;

这只能被一个空格字符分开,而不是全部空白。使preg_split会更容易分裂的任何空白

+0

我明白了,但是我怎么能像这样的段落回显数组? 这是一个 简单文本我 刚刚创建 – Gabriel 2011-03-31 19:03:49

+0

好吧,你需要使用foreach循环访问数组。但是看看你所做的新评论,使用这种方法,你还需要一个增量计数器和一个if来检查每隔三个单词后是否需要换行。但这可能不是最有效的方法 – Jase 2011-03-31 19:09:48

0

所以像...

function doLines($string, $nl){ 
    // Break into 'words' 
    $bits = explode(' ', $string); 
    $output = ''; 
    $counter=0; 
    // Go word by word... 
    foreach($bits as $bit){ 
    //Add the word to the output... 
    $output .= $bit.' '; 
    //If it's 3 words... 
    if($counter==2){ 
     // Remove the trailing space 
     $output = substr($output, 0, strlen($output)-1); 
     //Add the separator character... 
     $output .=$nl; 
     //Reset Counter 
     $counter=0; 
    } 
    } 
    //Remove final trailing space 
    $output = substr($output, 0, strlen($output)-1); 

    return $output; 
} 

然后你必须是:

echo doLines("This is a simple text I just created", "\n"); 

echo doLines("This is a simple text I just created", "<br />"); 

..取决于你是否想要换行或者是否需要HTML输出。

1

试试这就是你需要:

<?php 

$text = "This is a simple text I just created"; 

$text_array = explode(' ', $text); 

$i = 1; // I made change here :) 
foreach($text_array as $key => $text){ 

if(ceil(($key + 1)/3) != $i) { echo "<br/>"; $i = ceil(($key + 1)/3); } 
echo $text.' '; 
} 
?> 

结果:

This is a 
simple text I 
just created 
+0

尝试它,几个文本... – Faraona 2011-03-31 19:20:06

1
$text = "This is a simple text I just created"; 
$text_array = explode(" ", $text); 
$chunks = array_chunk($text_array, 3); 
foreach ($chunks as $chunk) { 
    $line = $impode(" ", $chunk); 
    echo $line; 
    echo "<br>"; 
}