使自定义替换的工作方式类似于PHP PDO的工作方式


Getting custom replace to work similar to how PHP PDO works

我只是想知道如何用数组不断替换某个索引字符,就像PDO在PHP中的工作方式一样?这是我的代码;

代码

    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>';

谢谢你的帮助,我希望我能得到。

$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>";

str_replace有一个可选的count参数,因此您可以让它一次替换一个出现。你可以循环遍历数组,替换元素n的下一个问号

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

感谢这些家伙的帮助,但是他们并没有按照我想要的方式工作。我已经找到了一个让它工作的方法。下面是代码

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;
}

如果有人有更好的方法,你可以告诉我,但现在这是可行的