zigojacko
zigojacko

Reputation: 2063

Replacing ampersand with the word and in URL's using existing str_replace

I'm needing to replace ampersand (&) with the word and in URL's and am already replacing spaces with hyphens using php str_replace like below:-

<?php echo strtolower(str_replace(' ', '-', $value)) ?>

Am I able to modify this to add the replacement of ampersands as well by using an array perhaps?

Upvotes: 0

Views: 5779

Answers (3)

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

To replace both strings in one statement, do the following;

<?php

$find = array(" ", "&");
$replace = array("-", "and");

$string = "Hello I am a man & I have a dog";

echo str_replace($find, $replace, $string); //Output: Hello-I-am-a-man-and-I-have-a-dog

http://codepad.org/nGj26mNc

A more elegant way would be to have one associative array. (http://codepad.org/OgogWK5l)

<?php

$findAndReplace = array(" " => "-", "&" => "and");

$string = "Hello I am a man & I have a dog";

echo str_replace(array_keys($findAndReplace), array_values($findAndReplace), $string);

Upvotes: 4

rack_nilesh
rack_nilesh

Reputation: 553

instead of replacing ampersand with a word, you can ecode it using encodeURIComponent() function.

Check this URL Encoding—Ampersand Problem

Upvotes: 0

Sumit Gupta
Sumit Gupta

Reputation: 2192

Answer to your question "if you are able to do using array" is yes. You should read documentation here : http://php.net/manual/en/function.str-replace.php

Also, if you just want to encode url you should try to use : https://www.php.net/manual/en/function.urlencode.php or https://www.php.net/manual/en/function.htmlentities.php

as per your requirement.

Upvotes: 0

Related Questions