使用子字符串从动态变量中删除字符

时间:2012-03-18 02:59:02

标签: php wordpress substring

我正在尝试使用substr从URL字符串中删除4个字符。目标是从字符串中删除.jpg并将其替换为“-220x124.jpg”。

我正在使用wordpress插件,高级自定义字段,但这不是问题。问题是该subst不能使用高级自定义字段代码the_sub_field。它返回整个URL字符串,不删除最后4个字符。知道为什么吗?

以下代码:

<?php if(get_field('still_uploads')): ?>
    <?php $i = 0; ?>
    <?php while(the_repeater_field('still_uploads') && $i <= 0 ): ?>

    <?php 
        $imagejesse =  the_sub_field('still_image');
        $imagejessenew = substr($imagejesse,0,-4); 
    ?>

    <?php echo $imagejessenew.'-220x124.jpg'; ?>
    <?php $i++ ?>
    <?php endwhile; ?>
<?php endif; ?>

您可以在此处查看示例:http://gicreative-dev.com/blog/genre/gay/

3 个答案:

答案 0 :(得分:1)

像这样使用strtr() function

$imagejessenew = strtr($imagejesse, array(
    '.jpg' => '-220x124.jpg',
));

查看此证明:http://ideone.com/B8ZQe

答案 1 :(得分:1)

试试这个:

<?php 
    $imagejessenew = substr(trim(the_sub_field('still_image')),0,-4);

    if($imagejessenew !== FALSE)
    {
        $imagejessenew .= '-220x124.jpg';
    }
    else
    {
        // Shit happened, the_sub_field('still_image') was shorter than 4 characters
    }
?>

答案 2 :(得分:1)

$imagejessenew = preg_replace('/(.*)(.(jpg|png|gif))$/i', '$1-220x124.$3', trim($imagejesse));