使用增量替换字符串一次替换一个字符串

发布于 2024-12-04 07:39:07 字数 281 浏览 0 评论 0原文

我有字符串 $var 我需要在其中替换一些文本。第一个X需要替换为A,第二个X需要替换为B,依此类推,这是一个示例:

$var = "X X X X"; // input
// some function
echo $var //the result: "A B C D"

我尝试使用 str_replace(),但这不起作用。

I have the string $var in which I need to replace some text. The first X needs to be replaced by A, the second X needs to be replaced by B and so on, here is an example:

$var = "X X X X"; // input
// some function
echo $var //the result: "A B C D"

I tried with str_replace(), but that doesn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

鼻尖触碰 2024-12-11 07:39:07

您可以使用 preg_replacelimit 参数只能替换一次。

<?php
    $var = 'X X X X';
    $replace = array('A', 'B', 'C', 'D');
    foreach($replace as $r)
        $var = preg_replace('/X/', $r, $var, 1);
    echo $var;
?>

http://codepad.viper-7.com/ra9ulA

You could use preg_replace's limit argument to only replace once.

<?php
    $var = 'X X X X';
    $replace = array('A', 'B', 'C', 'D');
    foreach($replace as $r)
        $var = preg_replace('/X/', $r, $var, 1);
    echo $var;
?>

http://codepad.viper-7.com/ra9ulA

皓月长歌 2024-12-11 07:39:07

您可以使用 preg_replace_callback()

// as many as you think you'll need, maximum.
// this can be programmatically generated, if need be
$replacements = array('A', 'B', 'C', 'D', 'E', 'F', 'G'); // and so on    

function get_replace_value($matches) {
    global $replacements;
    return array_shift($replacements);
}

$var = preg_replace_callback("/" + preg_quote($needle) + "/",
    "get_replace_value", $var);

You could use preg_replace_callback():

// as many as you think you'll need, maximum.
// this can be programmatically generated, if need be
$replacements = array('A', 'B', 'C', 'D', 'E', 'F', 'G'); // and so on    

function get_replace_value($matches) {
    global $replacements;
    return array_shift($replacements);
}

$var = preg_replace_callback("/" + preg_quote($needle) + "/",
    "get_replace_value", $var);
海未深 2024-12-11 07:39:07
$var = 'X X X X';
$replacements = array('A', 'B', 'C', 'D');

$var = preg_replace_callback('/X/', function() use (&$replacements) {
    return array_shift($replacements);
}, $var);

其他解决方案:

$var = preg_replace('/X/', 'A', $var, 1);
$var = preg_replace('/X/', 'B', $var, 1);
$var = preg_replace('/X/', 'C', $var, 1);
$var = preg_replace('/X/', 'D', $var, 1);

此解决方案使用 preg_replace 的 $limit 参数(我们每次调用仅替换一次出现的情况)。

$var = 'X X X X';
$replacements = array('A', 'B', 'C', 'D');

$var = preg_replace_callback('/X/', function() use (&$replacements) {
    return array_shift($replacements);
}, $var);

Other solution:

$var = preg_replace('/X/', 'A', $var, 1);
$var = preg_replace('/X/', 'B', $var, 1);
$var = preg_replace('/X/', 'C', $var, 1);
$var = preg_replace('/X/', 'D', $var, 1);

This one uses the $limit parameter of preg_replace (we replace only one occurrence per call).

摘星┃星的人 2024-12-11 07:39:07

不使用正则表达式

$arr = explode('X', 'X X X X');
$rep = array('A','B','C','D');
foreach ($arr as $idx=>$val)
{
  $arr[$idx] = $val.$rep[$idx];
}
echo implode($arr);

Without use of regex

$arr = explode('X', 'X X X X');
$rep = array('A','B','C','D');
foreach ($arr as $idx=>$val)
{
  $arr[$idx] = $val.$rep[$idx];
}
echo implode($arr);
荒路情人 2024-12-11 07:39:07

还有一个解决方案(对于动态数量的 X 来说更多):

<?php

  $foo = 'X X X X X X';

  $Xs = preg_match_all('/\bX\b/',$foo,$_); if ($Xs === false) $Xs = 0;
  $alphabet = range('A', chr(64 + $Xs));
  foreach ($alphabet as $letter){
    $foo = preg_replace('/\bX\b/', $letter, $foo, 1);
  }

  echo $foo;

我还在模式中添加了 \b ,以仅替换独立的 X,因此“FAUX PAS X”仅替换最后 X.

演示

alphabet_replace(更模块化的形式)

Yet one more solution (more for a dynamic number of Xs):

<?php

  $foo = 'X X X X X X';

  $Xs = preg_match_all('/\bX\b/',$foo,$_); if ($Xs === false) $Xs = 0;
  $alphabet = range('A', chr(64 + $Xs));
  foreach ($alphabet as $letter){
    $foo = preg_replace('/\bX\b/', $letter, $foo, 1);
  }

  echo $foo;

I also added the \b in to the pattern to only replace Xs that are free-standing, so "FAUX PAS X" only replaces the last X.

demo

alphabet_replace (more modular form)

君勿笑 2024-12-11 07:39:07

让我们也尝试一下,只是为了它;)

$input = "X X X X";

function replace($input, array $replacements)
{
    $replacer = function(array &$i, array &$r, &$o) use(&$replacer) {
        if (count($i) === 0 || count($r) === 0) return;

        $i_cur = array_shift($i);

        if (ctype_space($i_cur)) $o .= $i_cur;
        else $o .= array_shift($r);

        $replacer($i, $r, $o);
    };

    $replacer(str_split($input), $replacements, $output);

    return $output;
}

var_dump(replace($input, range('A', 'Z'))); 

Lets give it a shot, too, just for the heck of it ;)

$input = "X X X X";

function replace($input, array $replacements)
{
    $replacer = function(array &$i, array &$r, &$o) use(&$replacer) {
        if (count($i) === 0 || count($r) === 0) return;

        $i_cur = array_shift($i);

        if (ctype_space($i_cur)) $o .= $i_cur;
        else $o .= array_shift($r);

        $replacer($i, $r, $o);
    };

    $replacer(str_split($input), $replacements, $output);

    return $output;
}

var_dump(replace($input, range('A', 'Z'))); 
没有伤那来痛 2024-12-11 07:39:07

其他答案中发生了很多循环,这里有一个替代方案。

$var = 'X X X X X X X';
$replace = array('A', 'B', 'C', 'D');
$var = preg_replace(array_fill(0, count($replace), '/X/'), $replace, $var, 1);
echo $var; // A B C D X X X

Lots of loops are happening in the other answers, here's an alternative.

$var = 'X X X X X X X';
$replace = array('A', 'B', 'C', 'D');
$var = preg_replace(array_fill(0, count($replace), '/X/'), $replace, $var, 1);
echo $var; // A B C D X X X
勿忘初心 2024-12-11 07:39:07

所提出的问题没有提供替换的主列表,因此我假设替换的数量未知。我将增加替换值,而不是使用有限数组。

请记住,如果 $find 字符串来自不受信任的来源,则应调用 preg_quote() 来转义对正则表达式引擎具有特殊含义的字符。

do-while 循环:(演示)

$input = 'X X X X X X X X';
$find = 'X';
$replace = 'A';

do {
    $input = preg_replace("#$find#", $replace, $input, 1, $count);
    $replace = str_increment($replace);
} while ($count);
echo $input;
// A B C D E F G H

递归函数:(演示

$input = 'X X X X X X X X';

function incrementalReplace($subject, $find, $replace) {
    $subject = preg_replace("#$find#", $replace, $subject, 1, $count);
    if ($count) {
        $subject = incrementalReplace($subject, $find, str_increment($replace));
    }
    return $subject;
}

echo incrementalReplace($input, 'X', 'A');
// A B C D E F G H

滥用 finally:(Demo

$input = 'X X X X X X X X';
$find = 'X';
$replace = 'A';

echo preg_replace_callback(
         "#$find#",
         function() use (&$replace) {
             try {
                 return $replace;
             } finally {
                 $replace = str_increment($replace);             
             }
         },
         $input
     );
// A B C D E F G H

当然,以上所有技术也可以使用更加向后兼容的++字符串增量。 (演示

echo preg_replace_callback(
         "#$find#",
         function() use (&$replace) {
             return $replace++;
         },
         $input
     );

The asked question does not provide a master list of replacements, so I'll assume that the number of replacements is not known. Instead of working with a finite array, I'll increment the replacement values.

Bear in mind that if the $find string comes from a non-trusted source, then preg_quote() should be called upon it to escape characters with special meaning to the regex engine.

A do-while loop: (Demo)

$input = 'X X X X X X X X';
$find = 'X';
$replace = 'A';

do {
    $input = preg_replace("#$find#", $replace, $input, 1, $count);
    $replace = str_increment($replace);
} while ($count);
echo $input;
// A B C D E F G H

A recursive function: (Demo)

$input = 'X X X X X X X X';

function incrementalReplace($subject, $find, $replace) {
    $subject = preg_replace("#$find#", $replace, $subject, 1, $count);
    if ($count) {
        $subject = incrementalReplace($subject, $find, str_increment($replace));
    }
    return $subject;
}

echo incrementalReplace($input, 'X', 'A');
// A B C D E F G H

An abusive use of finally: (Demo)

$input = 'X X X X X X X X';
$find = 'X';
$replace = 'A';

echo preg_replace_callback(
         "#$find#",
         function() use (&$replace) {
             try {
                 return $replace;
             } finally {
                 $replace = str_increment($replace);             
             }
         },
         $input
     );
// A B C D E F G H

Of course, all of the above techniques can also use the more backward compatible ++ string incrementation. (Demo)

echo preg_replace_callback(
         "#$find#",
         function() use (&$replace) {
             return $replace++;
         },
         $input
     );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文