1

I added the following code to the theme's index.php file on one of my WordPress sites, so that a heading would appear on the search results page that includes the actual search term. In other words, if I search for the word blue, this heading would then read, Search results for: blue.

<?php
if ( is_search() ); ?>
<h3>Search results for: <?php print_r($_GET['s']); ?></h3>

The output isn't great however when a phase in quotes get placed into the search bar. In other words, if I search for the phrase "blue is a color", this heading then reads: Search resulst for: \"blue is a color\"

I'd like to know how to stop those backslashes from appearing. I've done some research but nothing I've found has worked. I'm a php beginner at most.

Jutta Duncan
  • 101
  • 2
  • 11

3 Answers3

2

just use echo:

<?php
if ( is_search() ); ?>
<h3>Search results for: <?php echo $_GET['s']; ?></h3>

you must "escape" this variable before you print it though! Imagine if someone wrote a <script> in the search bar that manpulated your site when it was printed. Read on here: Escaping variables. One example would be like this:

echo htmlspecialchars($_GET['s']);

This removes characters like < and > so nobody can print scripts or html into your site

Community
  • 1
  • 1
Jeff
  • 24,623
  • 4
  • 69
  • 78
  • It seems that this doesn't work for me (or maybe I just don't understand it well enough). The WordPress theme developer gave me this suggestion: `

    Search results for:

    ` Is this a good solution? It works.
    – Jutta Duncan Feb 11 '16 at 16:58
  • @JuttaDuncan yes that is fine for removing the slashes. you should still escape the input though. I don't know why you are getting the slashes, that must be happening somewhere else, but this will remove them just fine! – Jeff Feb 11 '16 at 17:24
  • Great!! Thank you so much. I'm using this now, and that seems to work well: `

    Search results for:

    `
    – Jutta Duncan Feb 11 '16 at 21:06
0

PHP allows you to easily be able to remove values from a String using the explode() command.

$fractor = explode("\", $_GET['s']);

You can call $fractor what you like, just remember that it becomes an array of all the split strings.

Reference: http://php.net/manual/en/function.explode.php

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
-1

Use print instead of print_r

<?php
if ( is_search() ); ?>
<h3>Search results for: <?php print($_GET['s']); ?></h3>

There is some difference in print_r & print

print

  • Outputs only a single string

  • Returns 1, so it can be used in an expression

  • e.g. print "Hello"

  • or, if ($expr && print "foo")

print_r()

  • Outputs a human-readable representation of any one value

  • Accepts not just strings but other types including arrays and objects, formatting them to be readable

  • Useful when debugging

  • May return its output as a return value (instead of echoing) if the second optional argument is given

saadeez
  • 1,588
  • 3
  • 11
  • 17