2014-02-20 108 views
0

我有這樣的腳本:PHP標籤系統

<?php 

    $string = "@Erol Simsir @Hakan Simsir"; 
    $output = preg_replace("/@([^\s]+)/", "<a href=\"?tag=$1\">$1</a>", $string); 
    echo $output; 

?> 

這個腳本會檢測所有的話,在他們面前的一個「@」符號,並將其變爲鏈接/標籤。然而,我不想要一個標籤系統,而是一個標籤系統,就像在Twitter上一樣,你可以在這裏做'@JohnDoe',用戶JohnDoe將成爲這個Tweet的人。

所以,我需要的是一個字符串的所有標記存儲在一個陣列事後把它們用於SQL查詢。

我怎樣才能做到這一點?

UPDATE

我現在所擁有的這樣的代碼:

$string = $_POST["tags"]; 
$output = preg_replace("/@([^\s]+)/", "<a href=\"?tag=$1\">$1</a>", $string); 
$finalOutput = explode(" ", $string); 
$count = count($finalOutput); 
$i = 0; 
while($i < $count) { 
echo $finalOutput[$i]; 
$i = $i + 1; 
} 

問題是,標籤看起來像這樣的輸出:@約翰@sandra等我怎樣才能刪除@符號輸出?

+0

'preg_match','explode','insert into' – Ohgodwhy

回答

1
$array = explode(' ', $string); 

試用一下這個代碼:)

$count = count($array); 
$tag_array = array(); 
$j=0; 
for($i=0;$i<$count;$i++) 
{ 
    if(substr($array[$i],0,1)==='@') 
    { 
    $tag= ltrim ($array[$i],'@'); 
    $tag_array[$j] = $tag; 
    $j++; 
    } 
} 

print_r($tag_array); 

讓我知道,如果你想進一步的幫助:)

+1

歡迎您:) 感謝您選擇正確答案.. –

1

最簡單的方法是使用preg_match_all

$string = "@Erol Simsir @Hakan Simsir"; 
preg_match_all("/@(\w+)/", $string, $output); 
print_r($output[0]); 
0

我看過這個腳本有問題:

$string = $_POST["tags"]; 
$output = preg_replace("/#([^\s]+)/", "<a href=\"?tag=$1\">$1</a>", $string); 
$finalOutput = explode(" ", $output); 
$count = count($finalOutput); 
$i = 0; 
while($i < $count) { 
    echo $finalOutput[$i] . "<br />"; 
    $i = $i + 1; 
} 

它還爆炸所有的話沒有@符號。當我在表單中插入'JohnDoe'時,它也會接受,但它應該只接受帶有@符號的文本。所以當我在腳本中插入'JohnDoe'時,它應該驗證並說這不是一個有效的標籤。只有當輸入像'@ john @steve'等時它應該工作。