【问题标题】:How to use preg_replace with url encoded $_GET?如何使用带有 url 编码的 $_GET 的 preg_replace?
【发布时间】:2020-04-10 16:43:20
【问题描述】:

我有一个类似https://URL.DOMAIN/blog.php?id=43&q=echo%20%27test%27 的网址。

当我使用<?php echo $_GET['q'] ?> 时,它会显示echo 'test',这正是我想要的。

我在 preg_replace 函数中使用这个变量,它基本上是为了在匹配的字符串下应用黄色背景:

preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);

它非常适用于“普通”字符串,如“apple”或其他字符串,但当搜索查询中有 ' 时,它不会匹配任何内容。

代码示例

$news_content = $news_display['news_description'];

if(isset($_GET['q'])){
   $news_content = preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
}

$news_display['news_description'] 包含从 DB 输出的文本。

【问题讨论】:

  • @AbraCadaver 回声输出和以前一样工作,但 preg_replace 仍然不匹配它应该的。
  • 需要展示完整的代码示例
  • 提供var_dump($news_content, '/\b('.$_GET['q'].')\b/iu')的结果。
  • @user3783243 : var_dump 只是显示字符串(5369)“新闻内容”,实际上没有替代品。 preg_replace 函数与内容不匹配
  • '/\b('.$_GET['q'].')\b/iu' 的值为空?至少应该是/\b\b/iu

标签: php regex preg-replace


【解决方案1】:

只需使模式贪婪? 并删除尾随的单词边界\b,因为' 不是单词字符而是单词边界:

$news_content = preg_replace('/\b('.$_GET['q'].'?)/iu',
                             '<span class="research-news-found">$1</span>',
                             $news_content);

Demo

但如果你希望它实际上会echo测试,那么不会。您需要重新构建您的问题以陈述您想要实现的目标,而不是如何让这个替代品发挥作用。

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2014-09-26
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    相关资源
    最近更新 更多