0

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?

zigojacko
  • 1,983
  • 9
  • 45
  • 77

3 Answers3

4

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);
ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
0

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 : http://in1.php.net/manual/en/function.urlencode.php or http://in1.php.net/manual/en/function.htmlentities.php

as per your requirement.

Sumit Gupta
  • 2,152
  • 4
  • 29
  • 46
  • I'm already looking at the `str_preplace` docs but could not find an example of what I'm trying to do. That is only when I posted here. It's all well and good posting links to documentation but I try that first before posting on here. – zigojacko Jul 11 '14 at 10:39
  • @zigojacko your question never suggest if you look for documentation and didn't find solution. However if you look for #2 example in documentation it shows how we can use Array Replace within function. :) so, you understand now why I post URL. "Reading is Best teacher"... – Sumit Gupta Jul 11 '14 at 10:56
  • I agree, it is - I was trying those examples but couldn't get it working - perhaps I should have explained that in my original question. Thanks. – zigojacko Jul 11 '14 at 11:01
0

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

Check this URL Encoding—Ampersand Problem

Community
  • 1
  • 1
rack_nilesh
  • 553
  • 5
  • 18
  • But the URL already exists with the word 'and' in. My string is like `one & two` and the URL, I need to match it to is `one-and-two`. – zigojacko Jul 11 '14 at 10:46