0

I have some string i have to fix from old code. i have something like this:

$str = 'a-b-x-d-e';
$str = 'bbbb-ccccc-y-ee-fff';
$str = 'aa-ee-z-jjjjjjjj-uuu';
$str = 'aa-ee-z-y-x';

the middle one is (x or y or z) is not valid anymore, and i have to replace it with either "m, n or p"

now, there's plenty way to do this, i was thinking to do:

$list = explode($str);
foreach($list as $k => $v) {
 //find the third one and replace it by rebuilding the string
}

but this seem very cumbersome and long to do, is there any faster way?

edit: I can also have the same values at any other position, which these are still valid.

2 Answers 2

1

Here's a simple one:

$str = 'a-b-x-d-e';

$newVar = 1;

$tmp = explode('-', $str);
$tmp[2] = $newVar;
$str = implode('-', $tmp);
unset($tmp);

echo $str;
Sign up to request clarification or add additional context in comments.

Comments

1

The simplest solution would be to use str_replace.

$list = str_replace(array('x', 'y', 'z'), array('m', 'n', 'p'), $list);

This will replace x with m, y with n etc..

The $list array should hold the list of your strings.

Here is the codepad: http://codepad.org/mC602d7Z

This is based off the fact that x y and z don't appear anywhere else.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.