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.
just use echo:
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:This removes characters like
<
and>
so nobody can print scripts or html into your sitePHP 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
Use
print
instead ofprint_r
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