爆炸在一条线上

时间:2012-02-17 10:58:20

标签: php explode

我想逐字逐句地爆炸文字,但是在一行中。不是逐行的。 我有这个:

$someWords = "Please don't blow me to pieces."; 
$test = '';
$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
    echo "Piece $i = $wordChunks[$i] <br />";
    $test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a> <br />';
} 

和此:

 echo $test;

这样看起来像这样:

Please
don't
blow
me
to
pieces

但我想这样:

Please don't blow me to pieces

每个单词都有一个链接。

6 个答案:

答案 0 :(得分:2)

删除<br />代码

echo "Piece $i = $wordChunks[$i] ";
$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a> ';

答案 1 :(得分:1)

它分成新线的原因是因为你把它们放了。只需删除<br> s:

即可
$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a>';

修改

您实际上可以使用正则表达式在一行中执行此操作:

$test = preg_replace(
  '/(\S+)(\s*)/', // Find every collection of non-whitespace characters, which may or may not be followed by whitespace
  '<a href="test.php?id=$1">$1</a>$2', // Replace it with a link and append whitespace, if any
  htmlspecialchars($someWords, ENT_QUOTES) // pass the input string through htmlspecialchars() to avoid broken HTML
);

See it working

答案 2 :(得分:1)

<br/>表示换行符。因此,如果您不希望在每个单词之间添加新行,请不要在每个单词之间加上<br/>

所以,而不是

$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a> <br />';

DO

$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a>';

答案 3 :(得分:0)

使用array_map(和implode将所有东西粘合成一个字符串):

$someWords = "Please don't blow me to pieces."; 
$words = explode(" ", $someWords);
$links = array_map(
    $words,
    function($w) { return '<a href="test.php?id='.$w.'">'.$w.'</a>'; });
echo implode('', $links);

如果您不介意可读性,可以在一行中完成。

答案 4 :(得分:0)

您手动包含换行符。只需删除<br />

即可
$someWords = "Please don't blow me to pieces."; 
$test = '';
$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
    echo "Piece $i = $wordChunks[$i] <br />";
    $test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a>';
} //                                                                         ^^^

答案 5 :(得分:0)

试试这个:

$someWords = "Please don't blow me to pieces.";
$test = '';
$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
    $test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a>&nbsp;';
} 
echo $test;