Array search and replace

with the following array

$array = ([1zxc] => ‘a/abc/m.htm’, [2zac] => ‘b/attachment/d.htm’, [3c] => ‘d/dsds/hre23.htm’, [4zac] => ‘k/attachment/d.htm’);

How can i replace in the array all ‘/attachment/’ for ‘/attach/’ and get…?

$array = ([1zxc] => ‘a/abc/m.htm’, [2zac] => ‘b/attach/d.htm’, [3c] => ‘d/dsds/hre23.htm’, [4zac] => ‘k/attach/d.htm’);

Hmm, there seems to be a lot of work going on for a simple task. Here is how I would do it.


$subject  = array ('/attachment/teste' => '123', 'xyz/attachment/test' => '456');
// 1. replace keys
$new_keys = str_replace('/attachment/', '/attach/', array_keys($subject));
// 2. combine new keys with the original values
$replaced = array_combine($new_keys, $subject);

print_r($replaced);

P.S. In the previous post, the second key does not get changed because the word is not attachment (check the number of "t"s).

hi, your code works… but not in all conditions.
look at the following, it unset the first array and does not replace the second one

$array1 = array ('/attachment/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?attachment=$matches[1]&cpage=$matches[2] [()/trackback/?$', 'xyz/atttachment/test' => 'index.php?attachment=$matches[1]&cpage=$matches[2] [()/trackback/?$');

function replaceKeys($key)
{
    return str_replace('/attachment/', '/attach/', $key);
}


$array1 = array_flip(array_map('replaceKeys', array_flip($array1))); 
print_r($array1);

however, if it is something like this… it works for the first element of the array, not the second…

$array1 = array ('/attachment/teste' => '123', 'xyz/atttachment/test' => '456');

function replaceKeys($key)
{
    return str_replace('/attachment/', '/attach/', $key);
}


$array1 = array_flip(array_map('replaceKeys', array_flip($array1))); 
print_r($array1);

I don’t think there’s a function to change both the keys and values. This gets the job done:

function replaceValues($value)
{
	return str_replace('/attachment/', '/attach/', $value);
}

function replaceKeys($key)
{
	return str_replace('za', 'TW', $key);
}

$array = array_map('replaceValues', $array);
$array = array_flip(array_map('replaceKeys', array_flip($array)));

Many thanks!
However, I did a mistake asking for the replacement. I need the following…

$Sarray = ([1zxc] => ‘a/abc/m.htm’, [2zac] => ‘b/attachment/d.htm’, [3c] => ‘d/dsds/hre23.htm’, [4zac] => ‘k/attachment/d.htm’);

replacing za for TW

$Sarray = ([1zxc] => ‘a/abc/m.htm’, [2TWc] => ‘b/attachment/d.htm’, [3c] => ‘d/dsds/hre23.htm’, [4TWc] => ‘k/attachment/d.htm’)

Presume I have to unset the 2zac and 4zac… How is the fastest way to do it?
Thanks again…

function replace($string)
{
   return str_replace('/attachment/', '/attach/', $string);
}

$array = array_map('replace', $string);