Jump to content

Replace between in a string


drisate

Recommended Posts

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.

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;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.