繁体   English   中英

如何替换字符串中的第一个匹配项?

[英]How to replace the first occurrence in a string?

我正在尝试替换每个问号“?” 在具有数组值的字符串中。

我需要检查一个字符串,并替换首次出现的“?” 在带有值的字符串中。 我每次都需要这样做

这是我尝试过的

function sprintf2($str='', array $values = array(), $char = '?')
{
    if (!$str){
        return '';
    }

    if (count($values) > 0)
    {
        foreach ($values as $value)
        {
            $str = preg_replace('/'. $char . '/', $value, $str, 1);
        }
    }

    echo $str;
}

但是我收到以下异常

preg_replace():编译失败:在偏移量0处无重复

下面显示了我如何调用该函数

    $bindings = array(10, 500);
    $str = "select * from `survey_interviews` where `survey_id` = ? and `call_id` = ? limit 1";
    sprintf2($str, $bindings);

我在这里做错了什么? 为什么会出现此异常?

使用str_replace而不是preg_replace ,因为您要替换文字字符串而不是正则表达式模式。

但是, str_replace始终替换所有匹配项,没有办法将其限制为仅第一个匹配项( preg_replace是类似的)。 第四个参数不是限制,它是一个变量,它设置为找到并替换的匹配数。 要只替换一个匹配项,可以将strpossubstr_replace结合substr_replace

function sprintf2($str='', array $values = array(), $char = '?')
{
    if (!$str){
        return '';
    }

    if (count($values) > 0)
    {
        $len = strlen($char);
        foreach ($values as $value)
        {
            $pos = strpos($str, $char);
            if ($pos !== false) {
                $str = substr_replace($str, $value, $pos, strlen($char));
            }
        }
    }

    echo $str;
}

演示

您需要转义“?” 使用反斜杠(“ \\?”而不是“?”)登录您的正则表达式。

但是您的代码可以很容易地重构为使用preg_replace_callback:

$params = array(1, 3);
$str = '? bla ?';
echo preg_replace_callback('#\?#', function() use (&$params) {
    return array_pop($params);
}, $str);

希望这段代码对您有所帮助。

function sprintf2($string = '', array $values = array(), $char = '?')
{
    if (!$string){
        return '';
    }

    if (count($values) > 0)
    {
        $exploded = explode($char, $string);
        $i = 0;
        $string = '';
        foreach ($exploded as $segment) {
            if( $i < count($values)){
                $string .= ($segment . $values[$i]);
                ++$i;
            }

        }
    }

    echo $string;
}

$bindings = array(10, 500);
$str = "select * from `survey_interviews` where `survey_id` = ? and `call_id`= ? limit 1";
echo sprintf2($str, $bindings);


说明:
在您的代码中,您使用的是preg_match,而preg_match方法中的第一个参数是正则表达式模式。 您要替换的是什么? 具有0或1个CHARACTER的有效含义。 所以,您必须通过执行\\来逃避该操作 尽管不需要转义所有字符,但是,为了使您的方法起作用,您必须检查对任何正则表达式均有效的字符。
在我的代码中,我将字符串拆分为所需的字符。 然后将这些值附加到我们从数组中得到的部分的末尾。 并且应该这样做直到值数组的值长度,否则将发生偏移错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM