How to strip slashes from search query

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”

Read More

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.

Related posts

3 comments

  1. 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

  2. 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

Comments are closed.