php 需要对变量中的指定字符串进行替换

<?php
$from = 'http://m.def.com/';
$ads = '你好';
$url = 'http://m.abc.com/?aa=123&bb=dddd-[from]-[ads]';

?>

要求:需要对$url用php语言进行替换,把[from]用变量$from替换,[ads]用$ads替换

阅读 4.9k
4 个回答

多看文档 str_replace

$url = str_replace(['[from]','[ads]'],[$from,$ads],$url);
<?php
$tpl['from'] = 'http://m.def.com/';
$tpl['ads'] = '你好';
$url = 'http://m.abc.com/?aa=123&bb=dddd-[from]-[ads]';

$url = preg_replace_callback('/\[(.*?)\]/', function ($matches) use ($tpl) {
  return $tpl[$matches[1]];
}, $url);

这样可以达到替换的目的,不知道是不是你想要的方式:

$str = str_replace('from', $from, $url);
$str = str_replace('ads', $ads, $str);
echo $str;

对上面的写法进行简化:
$str = str_replace('ads', $ads, str_replace('from', $from, $url));
echo $str;
推荐问题