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.

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.