2014-05-23 15 views
0

我只想知道如何使用数组不断地替换某个索引字符,例如PDO如何在PHP中工作?这是我的代码;获取自定义替换的工作方式与PHP PDO的工作方式类似

的代码

private $string; 

    public function __construct($string = null) { 
     if ($string !== null) { 
      $this->string = $string; 
     } else { 
      $this->string = ''; 
     } 
    } 

    public function getString() { 
     return $this->string; 
    } 

    public function replaceWith($index, $array = array()) { 
     $lastArrayPoint = 0; 
     $i = 0; 
     while ($i < sizeof($this->string)) { 
      if (substr($this->string, $i, $i + 1) == $index) { 
       $newString[$i] = $array[$lastArrayPoint]; 
       $i = $i . sizeof($array[$lastArrayPoint]); 
       $lastArrayPoint++; 
      } else { 
       $newString[$i] = $this->string[$i]; 
      } 
      $i++; 
     } 
     return $this; 
    } 

和执行代码

$string = new CustomString("if ? == true then do ?"); 
    $string->replaceWith('?', array("mango", "print MANGO")); 
    echo '<li><pre>' . $string->getString() . '</pre></li>'; 

谢谢你的帮助,我希望我会收到。

回答

0

感谢您的帮助球员,但他们没有工作,我想它的工作方式。我找到了一种让它工作的方法。这里是代码

public function replaceWith($index, $array = array()) { 
    $arrayPoint = 0; 
    $i = 0; 
    $newString = ""; 
    while ($i < strlen($this->string)) { 
     if (substr($this->string, $i, 1) === $index) { 
      $newString .= $array[$arrayPoint]; 
      $arrayPoint++; 
     } else { 
      $newString .= substr($this->string, $i, 1); 
     } 
     $i++; 
    } 
    $this->string = $newString; 
    return $this; 
} 

如果有人有更好的方法,那么你可以告诉我,但现在这个作品。

0
$string = "if %s == true then do %s. Escaping %% is out of the box."; 
$string = vsprintf($string, array("mango", "print MANGO")); 
echo "<li><pre>$string</pre></li>"; 
0

str_replace有一个可选的count参数,所以你可以把它在同一时间更换一个occurrance。你可以通过数组循环,更换下一个问号元件N

$string = "if %s == true then do %s"; 
$params = array("mango", "print MANGO"); 
foreach ($params as $param) 
    $string = str_replace('?', $param, $string, 1);