0

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
1
  • 1
    What is the original string? Commented Jan 29, 2015 at 7:58

5 Answers 5

2

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 = "-";
Sign up to request clarification or add additional context in comments.

Comments

1

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 = "-";

Fiddle

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.

Comments

1

Try this:

$replace = "-";

instead of

$replace = array("-");

Comments

0

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;

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.