drisate Posted September 11, 2008 Share Posted September 11, 2008 Hey guys, How can i replace X by _ between ( and ) in a giving string? Link to comment https://forums.phpfreaks.com/topic/123821-replace-between-in-a-string/ Share on other sites More sharing options...
Zhadus Posted September 11, 2008 Share Posted September 11, 2008 One way to do it would be to split the string by ( and then by ), take the values that are inbetween and replace all the X by _ in that new string value, then put it all back together. e.g. $stringArray = split("(", $string); $replacedValue = split(")", $stringArray[1]); $stringArray[0] // The value that holds the string before the ( $replacedValue[0] // The value that holds the string between ( and ) $replacedValue[1] // The value that holsd the string after the ) $replacedValue[0] = str_replace("X", "_", $replacedValue[0]); $newString = stringArray[0] . $replacedValue[0] . $replacedValue[1]; This is assuming there is only once instance of ( and ), otherwise a different way would certainly be simpler. Link to comment https://forums.phpfreaks.com/topic/123821-replace-between-in-a-string/#findComment-639329 Share on other sites More sharing options...
sasa Posted September 11, 2008 Share Posted September 11, 2008 or <?php $test = 'as X X 8 sdX(dX asXd) as X (ohXXX) X X'; for ($i = 0, $count = 0; $i < strlen($test); $i++){ switch ($test[$i]){ case '(' : $count++; break; case ')' : $count--; break; case 'X' : if($count) $test[$i] = '_'; break; } } echo $test; ?> Link to comment https://forums.phpfreaks.com/topic/123821-replace-between-in-a-string/#findComment-639365 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.