2013-04-25 41 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