用变量string替换所有子串实例

时间:2011-07-06 12:45:27

标签: php string replace

如果你有字符串

'Old string Old more string Old some more string'

你想得到

'New1 string New2 more string New3 some more string'
你会怎么做?

换句话说,你需要用变量字符串'New'替换'Old'的所有实例。$ i。有什么建议吗?

5 个答案:

答案 0 :(得分:6)

迭代解决方案,不需要正则表达式

$str = 'Old string Old more string Old some more string';
$old = 'Old';
$new = 'New';

$i = 1;

$tmpOldStrLength = strlen($old);

while (($offset = strpos($str, $old, $offset)) !== false) {
  $str = substr_replace($str, $new . ($i++), $offset, $tmpOldStrLength);
}
$offset中的

strpos()只是一点微优化。我不知道,它是否值得(事实上我甚至不知道,如果它改变了什么),但我们的想法是,我们不需要在子串中搜索$old,已经处理完毕。

请参阅Demo

Old string Old more string Old some more string
New1 string New2 more string New3 some more string

答案 1 :(得分:2)

使用preg_replace_callback

$count = 0;
$str = preg_replace_callback(
    '~Old~',
    create_function('$matches', 'return "New".$count++;'),
    $str
);

答案 2 :(得分:1)

来自str_replace上的PHP手册:

  

用替换字符串

替换所有出现的搜索字符串
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
     

搜索

     

正在搜索的值,也称为 。阵列可用于指定多个针。

     

替换

     

替换找到的搜索值的替换值。可以使用数组来指定多个替换。

     

受试者

     

正在搜索和替换的字符串或数组,也称为 haystack

     

如果 subject 是一个数组,则对 subject 的每个条目执行搜索和替换,并且返回值也是一个数组。

     

计数

     

如果通过,则将设置为执行的替换次数。

答案 3 :(得分:1)

怎么样:

$str = 'Old string Old more string Old some more string';
$i = 1;
while (preg_match('/Old/', $str)) {
    $str = preg_replace('/Old/', 'New'.$i++, $str, 1);
}
echo $str,"\n";

<强>输出:

New1 string New2 more string New3 some more string

答案 4 :(得分:1)

我有一些像KingCrunch这样的类似解决方案,但是他已经回答了这个问题,我想知道一个str_replace变体带有一个替换回调并想出了这个(Demo):

$subject = array('OldOldOld', 'Old string Old more string Old some more string');
$search = array('Old', 'string');
$replace = array(
    function($found, $count) {return 'New'.$count;},
    function($found, $count) {static $c=0; return 'String'.(++$c);}
);
$replace = array();

print_r(str_ureplace($search, $replace, $subject));

/**
 * str_ureplace
 * 
 * str_replace like function with callback
 * 
 * @param string|array search
 * @param callback|array $replace
 * @param string|array $subject
 * @param int $replace_count
 * @return string|array subject with replaces, FALSE on error.
 */
function str_ureplace($search, $replace, $subject, &$replace_count = null) {
    $replace_count = 0;

    // validate input
    $search = array_values((array) $search);
    $searchCount = count($search);
    if (!$searchCount) {
        return $subject;
    }
    foreach($search as &$v) {
        $v = (string) $v;
    }
    unset($v);
    $replaceSingle = is_callable($replace);    
    $replace = $replaceSingle ? array($replace) : array_values((array) $replace);
    foreach($replace as $index=>$callback) {
        if (!is_callable($callback)) {
            throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index));
        }
    }

    // search and replace
    $subjectIsString = is_string($subject);
    $subject = (array) $subject;
    foreach($subject as &$haystack) {
        if (!is_string($haystack)) continue;
        foreach($search as $key => $needle) {
            if (!$len = strlen($needle))
                continue;            
            $replaceSingle && $key = 0;            
            $pos = 0;
            while(false !== $pos = strpos($haystack, $needle, $pos)) {
                $replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : '';
                $haystack = substr_replace($haystack, $replaceWith, $pos, $len);
            }
        }
    }
    unset($haystack);

    return $subjectIsString ? reset($subject) : $subject;
}
相关问题