str_replace网址不起作用

时间:2018-07-19 15:45:04

标签: php wordpress str-replace

我正在尝试在我的Wordpress模板中通过str_replace更改图像的url,但是它不起作用。

代码如下:

$featured_img = get_the_post_thumbnail_url(get_the_ID(),'full');

$featured_img_url = str_replace("http://www.mydomain.it/",
                                "https://newdomain.it/mysite/", 
                                $featured_img );

<div style="width: 100%; 
            height: 100%; 
            background: url('<?php echo $featured_img_url; ?>') #fff top center; 
            background-size: cover; 
            border-radius: 1%; 
            min-height: 200px;"></div>

div背景不断回显原始网址。

我已经尝试过使用单引号和双引号。我在做什么错了?

编辑:如果有帮助,则此代码在Wordpress循环内运行。

编辑:这是在var_dump上使用$featured_img时得到的:

string(105) "http://www.staging1.serialfreaks.it/wp-content/uploads/2017/08/Game-Of-Thrones-7x07-The-Dragon-and-The-Wolf-11.png"

这是使用正确网址的完整循环:

<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); 

$featured_img = get_the_post_thumbnail_url(get_the_ID(),'full');

$featured_img_url = str_replace('http://www.staging1.serialfreaks.it/','https://s3.eu-central-1.amazonaws.com/serialfreaks/', $featured_img );

?>

<div class="row" style="padding-bottom: 20px;">
    <div class="col-md-5">
        <div style="width: 100%;
                    height: 100%;
                    background: url('<?php echo $featured_img_url; ?>') #fff top center;
                    background-size: cover;
                    border-radius: 1%;
                    min-height: 200px;">
        </div>

    ...

谢谢大家:)

2 个答案:

答案 0 :(得分:0)

尝试:

$featured_img_url = substr_replace("http://www.mydomain.it/", 
                                   "http://www.mydomain.it/".$featured_img, 23 );

让我知道你会得到什么。

答案 1 :(得分:0)

我认为您的$feature_img值很错误。当我运行您的代码时,它显示了预期的结果。您可以通过var_dump($featured_img)对其进行调试。它可能在您的网址上有一些不必要的字符或一些不必要的空格。当我尝试使用您发布的示例$feature_img网址:https://eval.in/1039310

时,请参见 DEMO
<?php
$featured_img = 'http://www.mydomain.it/uploads/file.jpg';
echo "Before Replace=$featured_img\n";
$featured_img_url = str_replace("http://www.mydomain.it/","https://newdomain.it/mysite/", $featured_img );
echo  "After Replace=$featured_img_url\n\n";
?>
<div style="width: 100%; 
            height: 100%; 
            background: url('<?php echo $featured_img_url; ?>') #fff top center; 
            background-size: cover; 
            border-radius: 1%; 
            min-height: 200px;"></div> 

程序输出

Before Replace=http://www.mydomain.it/uploads/file.jpg
After Replace=https://newdomain.it/mysite/uploads/file.jpg

<div style="width: 100%; 
            height: 100%; 
            background: url('https://newdomain.it/mysite/uploads/file.jpg') #fff top center; 
            background-size: cover; 
            border-radius: 1%; 
            min-height: 200px;"></div>