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

孤街醉人 提交于 2020-01-25 07:01:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!