【问题标题】:Merging preg_match_all and preg_replace合并 preg_match_all 和 preg_replace
【发布时间】:2013-04-25 12:53:23
【问题描述】:

我正在运行一些代码,它可以找出字符串中的主题标签并将它们转换为链接。我已经使用preg_match_all 完成了此操作,如下所示:

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_replace 代码从preg_match_all 运行结果字符串,但是如果标签和搜索的字符串相同怎么办?第二个块也会加粗我的标签,这是不需要的。

更新根据下面给出的答案我正在运行的代码,但它仍然不起作用

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 循环中进行,该循环正在生成列表

【问题讨论】:

  • 谁能提出一些建议/
  • 你能发布完整的while循环吗?

标签: php preg-replace preg-match-all


【解决方案1】:

您只需要修改搜索模式以避免以“#”开头的搜索模式

$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);

【讨论】:

  • 那么我很确定有一个你能想到的解决方法
  • 如果查询是"bla",字符串是"#blabla"怎么办?
  • @Jack 好点,我添加了\b 字边界以防止这种情况发生。
  • @Jack 不工作。我的意思是也没有抛出错误。我把它放在我上面给出的带有preg_match_all 的标签搜索代码之后,但没有发生任何事情
  • @coder101 你能添加你正在运行的代码的更新版本吗?
猜你喜欢
  • 2013-07-17
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多