简体   繁体   中英

How to use preg_replace with url encoded $_GET?

I have a an url which looks like this https://URL.DOMAIN/blog.php?id=43&q=echo%20%27test%27 .

When I use <?php echo $_GET['q']?> it displays echo 'test' which is what I want.

I am using this variable inside a preg_replace function which is basically made to apply a yellow background under matched strings:

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

It works perfectly for "normal" strings like "apple" or whatever, but when there is a ' inside the search query it doesn't match anything.

Code example

$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'] contains the text output from DB.

Just make the pattern greedy ? and remove the trailing word boundary \b since ' is not a word character and is a word boundary:

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

Demo

But if you are hoping that it will actually echo test , then no. You would need to restructure your question to state what you want to achieve, not how to get this replacement to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM