2017-01-11 207 views
1

我有一个这样的输入: $input="12050301000000000000";替换所有的字符串,除了两个指标

我试图用preg_replace改变我输入0每一件事情,除了通过它们的索引引用的2个字符的。

例如我想,除了第一和第二字符的替换一切为0

我尝试这样做:

$input="02050301000000000000"; 
$index1=0; 
$index2=1; 
$output= preg_replace('/(?!^'.$index1.')/', '0', $input); 
+6

为什么不是一个简单的:'$输出= str_repeat( '0',strlen的($输入)); $ output [$ index1] = $ input [$ index1]; $ output [$ index2] = $ input [$ index2];',这会比正则表达式更容易阅读和理解 –

+1

在评论中无法获得比这更好的答案! –

+1

@MarkBaker我喜欢你的答案,你可以发布它作为答案,以便我可以接受它。 –

回答

-1

假设要替换1个3索引值2和5 :

$string = '02050301000000000000'; 
 
$patterns = array(); 
 
$patterns[1] = '/2/'; 
 
$patterns[3] = '/5/'; 
 
$replacements = array(); 
 
$replacements[1] = '0'; 
 
$replacements[3] = '0'; 
 
$output = preg_replace($patterns, $replacements, $string); 
 
var_dump($output);

输出: 2和5与0

string(20) "00000301000000000000"
取代详情对在使用的preg_replace索引数组看看: http://php.net/manual/en/function.preg-replace.php

0
function replace($string, $replace) { 
    $args = func_get_args(); 
    $string = array_shift($args); 
    $replace = array_shift($args); 
    $len = strlen($string); 
    $i = 0; 
    $result = ''; 
    while($i < $len) { 
     $result .= !in_array($i, $args) ? $replace : $string[$i]; 
     $i++; 
    } 
    return $result; 
} 

函数接受任意数目的在$ string和$ replace之后的索引(int)

$input="12050301000000000000"; 
echo $input; 
echo '<br>'; 
echo replace($input, 'a', 1, 3, 5, 7); 
0

这是我的工作

$input="02050301000000000000"; 
$index1=0; 
$output = preg_replace("/[^".$index1."+?!^]/", '0', $input); 

谢谢。

+0

if preg_replace(“/[^".$ index1。”+?!^] /“,'8',$ input);它将被替换为08080808000000000000替换为零谢谢.. –

相关问题