问题
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?
回答1:
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);
回答2:
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.
回答3:
instead of replacing ampersand with a word, you can ecode it using encodeURIComponent() function.
Check this URL Encoding—Ampersand Problem
来源:https://stackoverflow.com/questions/24695656/replacing-ampersand-with-the-word-and-in-urls-using-existing-str-replace