2012-02-17 9 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 

그리고 모든 단어에는 리가 있습니다. nk.

+1

내가 – m0skit0

+0

지금 내가보기 무엇을 얻고 무엇을 당신이 원하는 ... 사이의 차이를 볼 수 없습니다. 원하는 방식은 원래 문자열과 동일합니다 ... – m0skit0

답변

1

새로운 줄로 구분하는 이유는 그것을 넣었 기 때문입니다. 그냥 <br>의 제거 :

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