【问题标题】:str_replace - how to handle special circumstances? [duplicate]str_replace - 如何处理特殊情况? [复制]
【发布时间】:2011-03-15 07:35:38
【问题描述】:

可能重复:
PHP str_replace with for loop from array

如何用数组中的元素替换字符串(#stringA#)?...假设我们有一个文本:

'My shoes are #stringA# but #stringA#'(同一个字符串 - #stringA#)

与 $array:

$array[0] = 'comfy';
$array[1] = 'smells horrible';

所以它等于'My shoes are ' . $array[0] . ' but ' . $array[1]; - 我的鞋子很舒服但闻起来很臭?

【问题讨论】:

    标签: php str-replace


    【解决方案1】:

    通常在这种情况下,您会使用 %s 作为字符串替换,然后使用 vsprtinf() 将出现的 %s 替换为数组中的值。但是,在像您这样的简单情况下,您也可以将搜索字符串替换为 %s 并达到相同的效果。例如:

    <?php
    
    $string = 'My shoes are #stringA# but #stringA#';
    $key = "#stringA#";
    
    $array[0] = 'comfy';
    $array[1] = 'smells horrible';
    
    $string = str_replace(array('%', $key), array('%%', '%s'), $string);
    $newstring = vsprintf($string, $array);
    
    echo $newstring;
    
    ?>
    

    (将 % 替换为 %% 是为了避免一般情况下 printf 符号出现任何问题)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多