我可以在一个字符串中使用str_replace两次吗?

Cod*_*ody 1 php str-replace

<?php
echo "I'm currently listening to</a> <a href='http://last.fm/artist/" . str_replace(" ","+",$artist) . "/_/"  . str_replace(" ","+",$currenttrack) . "'>" . $currenttrack . "</a>";
?>
Run Code Online (Sandbox Code Playgroud)

以上是我的代码.我想str_replace()再次使用$artist$currenttrack喜欢:

str_replace("'","%27",$artist)str_replace("'","%27",$currenttrack)

因为撇号没有正确地通过我的代码混乱,但是当我首先使用空格时,它已经通过并且不会再次改变.

我能做什么?

Bar*_*mar 5

如果要对同一个字符串进行多次替换,可以将数组传递给str_replace:

str_replace(array(" ", "'"), array("+", "%27"), $artist)
Run Code Online (Sandbox Code Playgroud)

但是,在创建URL参数时,您不应自行进行替换.您应该使用urlencode,它将执行所有必要的编码.

  • +1 ..不知道为什么有人贬低了这个答案,它是唯一一个使用str_replace实际解决它的人 (2认同)