Reputation: 1165
I am getting data from a different server and in that there a string (title) of a post which is also being passed to my server . i am trying to filter out the unwanted spaces and characters but it does not seems to work . The code i made is
$find = array("%"," ","&","%20");
$replace = array("-");
$post_filtered_name=strtolower(str_replace($find,$replace,$post_title));
But i get the result
benten
instead of that i should get
ben-ten
Upvotes: 0
Views: 81
Reputation: 57
You are trying to filter out many unwanted and extra characters from the string by passing an array $find
. So you also have to give the replacement string for each search element individually.
So here you have to replace this
$replace = array("-");
with
$replace = array("-","-","-","-");
Number of index in $find
and $replace
has to be same.
Upvotes: 0
Reputation: 9782
Try this in case of converting string:
$post_title="ben ten%20Hero";
$post_filtered_name=strtolower(preg_replace('/(\%|\s)+/', '-', urldecode($post_title)));
echo $post_filtered_name;
Upvotes: 0
Reputation: 1963
See the section about the parameters here:
http://php.net/manual/en/function.str-replace.php
If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values.
However:
If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.
So instead:
$replace = array("-");
just use:
$replace = "-";
Upvotes: 2
Reputation: 46900
Since you have only one replacement for all the needles, don't make it an array. Pass it as a string and rest is already fine.
$replace = "-";
This can also be confirmed from the PHP Manual
If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.
Upvotes: 1