“递归地”更改字符串在 PHP 中
我想使用多个条件来更改字符串(在 PHP 中)来定义应进行哪些更改、更新字符串并继续更改更新后的字符串。
例如,从一个字符串开始,根据一个条件,对字符进行更改,然后使用该字符串的第二个版本,并根据另一个条件,再更改一些,依此类推,这样在过程结束时,变化已经累积。
显然,变量作用域阻止了以下方法:
$newstring = "This is a test string";
$value[] // This is an array already defined.
for ($i = 0; $i<=count($value); $i++) {
switch ($value[$i]) {
case -1:
$newstring = preg_replace(// do something with $newstring);
break;
case 0:
$newstring = preg_replace ( // do something else with $newstring);
break;
case 1:
$newstring = substr_replace(//do something else with $newstring);
break;
}
}
有没有办法实现这一点?
提前致谢。
更新:这是我的代码。正如您所料,$_POST['text1']
是一个字符串,$_POST['array']
是一个二维数组。
$text1 = $_POST['text1'];
$value = $_POST['array'];
for ($i = 0; $i<=count($value); $i++) {
switch ($value[$i][0]) {
case -1:
$newstring = preg_replace("/".$value[$i][1]."/","",$text1,1);
break;
case 0:
break;
case 1:
$newstring = substr_replace($text1, $value[$i][1],$value[$i][2],0);
break;
}
}
I want to change a string (in PHP) using several conditionals to define which change should be made, update the string and keep changing the updated string.
For example, start with a string and based on a condition, make a change in the character, then use the second version of the string, and based on another condition, change it some more, and so on, in such a way that at the end of the process, the changes have been cumulative.
Apparently, variable scope prevents the following approach:
$newstring = "This is a test string";
$value[] // This is an array already defined.
for ($i = 0; $i<=count($value); $i++) {
switch ($value[$i]) {
case -1:
$newstring = preg_replace(// do something with $newstring);
break;
case 0:
$newstring = preg_replace ( // do something else with $newstring);
break;
case 1:
$newstring = substr_replace(//do something else with $newstring);
break;
}
}
Is there a way to accomplish this?
Thanks in advance.
UPDATE: Here is my code. As you can expect, $_POST['text1']
is a string and $_POST['array']
is a two dimensional array.
$text1 = $_POST['text1'];
$value = $_POST['array'];
for ($i = 0; $i<=count($value); $i++) {
switch ($value[$i][0]) {
case -1:
$newstring = preg_replace("/".$value[$i][1]."/","",$text1,1);
break;
case 0:
break;
case 1:
$newstring = substr_replace($text1, $value[$i][1],$value[$i][2],0);
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将通过每次替换 text1 上的文本来覆盖对 newstring 的更改。您需要通过在各处使用 newstring 来保留这些更改。
You are overwriting your changes to newstring, by replacing text on text1 everytime. You need to preserve those changes by using newstring everywhere.