2014-05-23 13 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);