我需要做一些包括使用爆炸来创建数组的函数。我看过几个例子,但最后我真的很困惑!有一个简单的可读方式吗? (//注释?)PHP> echo字符串,每行3个字符分隔?
就拿一段文字:
"This is a simple text I just created".
输出应该是这样的:
This is a
simple text I
just created
所以爆炸应该文本拆分成3行每个字。
我需要做一些包括使用爆炸来创建数组的函数。我看过几个例子,但最后我真的很困惑!有一个简单的可读方式吗? (//注释?)PHP> echo字符串,每行3个字符分隔?
就拿一段文字:
"This is a simple text I just created".
输出应该是这样的:
This is a
simple text I
just created
所以爆炸应该文本拆分成3行每个字。
使用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
?>
爆炸刚刚拆分在指定字符的字符串。没有什么更多。
explode(',','Text,goes,here');
这会在字符串遇到a时分割字符串,并返回一个数组。
用空格字符
爆炸(””, '文字放在这里')分裂;
这只能被一个空格字符分开,而不是全部空白。使preg_split会更容易分裂的任何空白
所以像...
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输出。
试试这就是你需要:
<?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
尝试它,几个文本... – Faraona 2011-03-31 19:20:06
$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>";
}
我想我们可能需要更多的澄清一下。你想要爆炸什么,你想用数组做什么? – 2011-03-31 18:54:51
我不明白问题,你到底需要什么? – Faraona 2011-03-31 18:55:54
对不起,拿一个文本>“这是我刚刚创建的一个简单的文本”。 输出应该是这样的: 这是我 就创建了一个 简单的文本 所以爆炸应该文本拆分成每3个字线。 – Gabriel 2011-03-31 18:56:07