Php 一字排开

Php 一字排开,php,explode,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 h

我想逐字分解文本,但只在一行中。不是一行一行。 我有这个:

$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 />';
} 
有了这个,它看起来像这样:

Please
don't
blow
me
to
pieces
但我希望这样:

Please don't blow me to pieces

每个单词都有一个链接。

它被分隔成新行的原因是你把它们放在了一起。只需卸下s:

编辑

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

$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
);
移除标签

表示换行。所以,如果你不想在每个单词之间加一行,不要在每个单词之间加一个

因此,与其

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

使用array_map并内爆将所有内容粘合回字符串:

$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);

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

您正在手动包含换行符。只需删除:

试试这个:

$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;

我看不出你得到的和你想要的有什么区别……现在我明白了。您想要的方式与原始字符串相同。。。
$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a> <br />';
$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a>';
$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);
$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>';
} //                                                                         ^^^
$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;