2012-02-17 45 views
-1

我想逐字地分解文本,但在一行中。不是一行一行。 我有這樣的:分解成一行

$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 

每個字都有一個li NK。

+1

我不明白你們之間在說什麼,你想要什麼... – m0skit0 2012-02-17 11:00:07

+0

現在我看到它的任何區別。你想要的方式與原始字符串相同... – m0skit0 2012-02-17 11:01:29

回答

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

刪除<br />標籤

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

<br/>表示換行符。因此,如果您不想在每個單詞之間換行,請勿在每個單詞之間加上<br/>

所以,與其

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

$test .='<a href="test.php?id='.$wordChunks[$i].'">'.$wordChunks[$i].'</a>'; 
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); 

你可以這樣做如果您不介意可讀性,請在一行中。

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>'; 
} //                   ^^^ 
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;