2013-04-25 50 views
0

我有一些代碼正在運行,它會在字符串中找到hashtags並將它們變成鏈接。我這樣做使用preg_match_all如下圖所示:合併preg_match_all和preg_replace

if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){ 
foreach ($arrHashTags[1] as $strHashTag) { 
    $long = str_replace($strHashTag, '<a href="#" class="hashLinks">'.$strHashTag.'</a>', $postLong); 

    } 
} 

而且,我的搜索腳本,我需要大膽的關鍵字搜索結果中的字符串。同樣的事情也使用preg_replace下面的代碼:

$string = "This is description for Search Demo"; 
$searchingFor = "/" . $searchQuery . "/i"; 
$replacePattern = "<b>$0<\/b>"; 
preg_replace($searchingFor, $replacePattern, $string); 

,我遇到的問題是,這兩個要一起努力,應該拋出一個綜合作用的結果。我能想到的一種方法是從preg_match_allpreg_replace代碼運行結果字符串,但如果標記和搜索的字符串是相同的呢?第二個塊也會粗體顯示我的標籤,這也是不需要的。

更新代碼我是總部設在下面給出的答案運行,但它仍然無法正常工作

if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){ 
foreach ($arrHashTags[1] as $strHashTag) { 
    $postLong = str_replace($strHashTag, '<a href="#" class="hashLinks">'.$strHashTag.'</a>', $postLong); 

    } 
} 
在此之後

而且,我立即運行此

$searchingFor = "/\b.?(?<!#)" . $keystring . "\b/i"; 
$replacePattern = "<b>$0<\/b>"; 
preg_replace($searchingFor, $replacePattern, $postLong); 

正是如此你知道,這是一個while循環內,這是產生的列表

+0

有人可以提出一些建議/ – coder101 2013-04-25 15:33:41

+0

你可以發佈完整的while循環嗎? – miah 2013-04-27 13:04:35

回答

0

你只需要修改你的搜索模式,以避免那些以「#」

$postLong = "This is description for Search Demo"; 

if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){ 
    foreach ($arrHashTags[1] as $strHashTag) { 
    $postLong = str_replace($strHashTag, '<a href="#" class="hashLinks">'.$strHashTag.'</a>', $postLong); 
    } 
} 

# This expression finds any text with 0 or 1 characters in front of it 
# and then does a negative look-behind to make sure that the character isn't a # 
searchingFor = "/\b.?(?<!#)" . $searchQuery . "\b/i"; 
$replacePattern = "<b>$0<\/b>"; 
preg_replace($searchingFor, $replacePattern, $postLong); 

或者,如果你不需要使用哈希數組的另一個原因是,你只能使用的preg_replace開始。

$postLong = "This is description for #Search Demo"; 

$patterns = array('/(#[A-z_]\w+)/', "/\b.?(?<!#)" . $searchQuery . "\b/i"); 
$replacements = array('<a href="#" class="hashLinks">'.$0.'</a>', ' "<b>$0<\/b>'); 
preg_replace($patterns, $replacements, $postLong); 
+0

然後我很確定有一個解決方法,你可以想到 – coder101 2013-04-25 15:58:22

+0

@ coder101修復。 – miah 2013-04-25 18:56:52

+0

如果查詢是「bla」而string是'「#blabla」'會怎麼樣? – 2013-04-25 19:30:06