2011-04-14 50 views
0

我需要從字符串中提取一些文本,然後用一個字符在一個實例中刪除而不是另一個字符替換該文本。希望這個例子會告訴你我的意思是(這是我至今):在preg_replace函數期間刪除字符

$commentEntry = "@Bob1990 I think you are wrong..."; 
$commentText = preg_replace("/(@[^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=${1}$1\">$1</a>", $commentEntry); 

我想要得到的結果是:

<a href="http://www.youtube.com/comment_search?username=Bob1990">@Bob1990</a> I think you are wrong... 

但我越來越:

<a href="http://www.youtube.com/[email protected]">@Bob1990</a> I think you are wrong... 

我一直在處理這個問題至少一個小時,幾乎放棄了希望,所以任何幫助都非常感謝!

回答

3

可以嘗試這樣的事情

$commentText = preg_replace("/(@)([^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=$2\">$1$2</a>", $commentEntry); 
0

你可以做的是適應捕獲。移動@了括號:

preg_replace("/@([^\s]+)/", 

然後,你可以寫你的替換字符串像

'<a href="...$1">@$1</a>' 

注意如何第一$1剛剛重新插入文本,第二$1被逐字@前綴將其恢復。

0

您正在捕獲@,因此在使用$1時它會始終輸出。試試這個:

$commentText = 
    preg_replace(
    "/@([^\s]+)/", 
    "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=$1\">@$1</a>", 
    $commentEntry 
); 

這裏的區別是,@不再捕獲作爲$1(部分即它會只捕獲Bob1990因爲它是一個文本值,它並不需要成爲其中的一部分。任何模式,相反,我只是將其改爲在元素文本中直接輸出爲文本值,即直接輸入到捕獲的名稱之前(即它現在確實爲<a>@$1</a>而不是<a>$1</a>

相關問題