开发者

changing a string 'recursively' in PHP

开发者 https://www.devze.com 2023-02-13 21:50 出处:网络
I want to change a string (in PHP) using several conditionals to 开发者_如何学Pythondefine which change should be made, update the string and keep changing the updated string.

I want to change a string (in PHP) using several conditionals to 开发者_如何学Pythondefine 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;
    }

}


You are overwriting your changes to newstring, by replacing text on text1 everytime. You need to preserve those changes by using newstring everywhere.

$text1 = $_POST['text1'];
$value = $_POST['array'];
$newstring = $text1;
for ($i = 0; $i<=count($value); $i++) {
 switch ($value[$i][0]) {


    case -1:
       $newstring = preg_replace("/".$value[$i][1]."/","",$newstring,1);
        break;
    case 0:
        break;
    case 1:
        $newstring = substr_replace($newstring, $value[$i][1],$value[$i][2],0);
        break;
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消