使用现有的 str_replace 用单词和 URL 替换 & 号

问题描述:

我需要用 URL 中的单词 and 替换与号 (&),并且我已经使用 php 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?

要在一个语句中替换两个字符串,请执行以下操作;

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

一种更优雅的方式是拥有一个关联数组.(http://codepad.org/OgogWK5l)

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);