2011-05-23 41 views
1

如果此腳本檢測到,然後顯示所有#標籤,我該如何更改它,使它們都成爲超鏈接?基本上把它的一個<a href="#">盈和</a>背後如何將所有#標籤變爲超鏈接?

$str = <<<STR 
this is a string 
with a #tag and 
another #hello one 
STR; 

$matches = array(); 
if (preg_match_all('/#([^\s]+)/', $str, $matches)) { 
    var_dump($matches[1]); 
} 
+0

我不知道我理解。你能舉個例子嗎? – 2011-05-23 15:22:27

+1

他希望'#tag'變成'#tag'。 – 2011-05-23 15:26:33

回答

1

可以使用反向引用,並preg_replace做到這一點。

echo preg_replace('/#([^\s]+)/', '<a href="#">$1</a>', $str); 

輸出:

this is a string 
with a <a href="#">tag</a> and 
another <a href="#">hello</a> one 

如果你想在#是鏈接的一部分,只需將正則表達式更改爲/(#[^\s]+)/

演示:http://ideone.com/T06HQ

-3
sed 's/#/URL/' myhtmlfile.html 

其中URL是你要替換#與URL。

+0

他想用'#tag'代替'#標籤',而且他也想在他的PHP腳本里面做。 – 2011-05-23 15:42:48

2

這聽起來像你想這樣做:

$str = <<<STR 
this is a string 
with a #tag and 
another #hello one 
STR; 

$matches = array(); 
if (preg_match_all('/#([^\s]+)/', $str, $matches)) { 
    // Get rid of the full matches 
    array_shift($matches); 
    // Now get the first array element which are the actual captured matches 
    list($matches) = $matches; 

    foreach($matches as $match) { 
    echo "<a href='#'>{$match}</a>\n"; 
    } 
} 

輸出:

$ php test.php 
<a href='#'>tag</a> 
<a href='#'>hello</a>