Replace string in an array with PHP - php

How can I replace a sub string with some other string for all items of an array in PHP?
I don't want to use a loop to do it. Is there a predefined function in PHP that does exactly that?
How can I do that on keys of array?

Why not just use str_replace without a loop?
$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);

$array = array_map(
function($str) {
return str_replace('foo', 'bar', $str);
},
$array
);
But array_map is just a hidden loop. Why not use a real one?
foreach ($array as &$str) {
$str = str_replace('foo', 'bar', $str);
}
That's much easier.

This is a very good idea that I found and used successfully:
function str_replace_json($search, $replace, $subject)
{
return json_decode(str_replace($search, $replace, json_encode($subject)), true);
}
It is good also for multidimensional arrays.
If you change the "true" to "false" then it will return an object instead of an associative array.
Source: Codelinks

I am not sure how efficient this is, but I wanted to replace strings in a big multidimensional array and did not want to loop through all items as the array structure is pretty dynamic.
I first json_encode the array into a string.
Replace all the strings I want (need to use preg_replace if there are non-English characters that get encoded by json_encode).
json_decode to get the array back.

function my_replace_array($array,$key,$val){
for($i=0;$i<count($array);$i++){
if(is_array($array[$i])){
$array[$i] = my_replace_array($array[$i],$key,$val);
}else{
$array[$i]=str_replace($key,$val,$array[$i]);
}
}
return $array;
}

With array_walk_recursive()
function replace_array_recursive( string $needle, string $replace, array &$haystack ){
array_walk_recursive($haystack,
function (&$item, $key, $data){
$item = str_replace( $data['needle'], $data['replace'], $item );
return $item;
},
[ 'needle' => $needle, 'replace' => $replace ]
);
}

$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);
$basket = array_replace($base, $replacements);

Related

How to convert String Array to php Array?

How to convert Sting Array to PHP Array?
"['a'=>'value one','key2'=>'value two']"
to
$data=['a'=>'value one','key2'=>'value two'];
Please let me know if anyone knows of any solution
I want to take array input via textarea. And I want to convert that to a PHP array.
When I'm through textarea
['a'=>'value one','key2'=>'value two']
This is happening after submitting the from
"['a'=>'value one','key2'=>'value two']"
Now how do I convert from this to PHP Array?
Assuming you are not allowing multi dimensional arrays, this will work:
$stringArray = "['a'=>'value one','key2'=>'value two']";
$array = array();
$trimmedStringArray = trim( $stringArray, '[]' );
$splitStringArray = explode( ',', $trimmedStringArray );
foreach( $splitStringArray as $nameValuePair ){
list( $key, $value ) = explode( '=>', $nameValuePair );
$array[$key] = $value;
}
Output:
Array
(
['a'] => 'value one'
['key2'] => 'value two'
)
You will probably want to do some error checking to make sure the input is in the correct format before you process the input.
Extremely unsafe version using eval():
<?php
$a = "['a'=>'value one','key2'=>'value two']";
eval('$b = '.$a.';');
print('<pre>');
print_r($b);
Use only when you are sure, that other people can't use your textarea input!
Using replacements to convert this to json is a much better option for public forms. Additionally, if you use this at your work, you probably would get fired :)
With syntax error catch:
<?php
$a = "['a'=>'value one','key2'=>'value two'dsbfbtrg]";
try {
eval('$b = '.$a.';');
} catch (ParseError $e) {
print('Bad syntax');
die();
// or do something about the error
}
print('<pre>');
print_r($b);
Another option:
<?php
$string = "['a'=>'value one','key2'=>'value two']";
$find = ["'", "=>", "[", "]"];
$replace = ["\"", ":", "{", "}"];
$string = str_replace($find, $replace, $string);
$array = json_decode($string, true);
var_dump($array);
?>

explode string to multidimensional with regular expression

I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);

replace all keys in php array

This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144
You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.
Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}
We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}
Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)

Format the string using sprintf

I have this string:
"[\"form\",\"form-elements\"], [\"company\",\"asdasd\"], [\"cod_postal\",\"051768\"], [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"], [\"recaptcha_response_field\",\"168\"]"
This string was formated form an array using this code:
function arrayDisplay($input)
{
return implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$input,
array_keys($input)
)
);
}
And encoded using :
$xml_array = arrayDisplay($_POST);
$xml_encode = json_encode($xml_array);
And this is the array in $_POST variable:
array (size=5)
'form' => string 'form-elements' (length=13)
'company' => string 'asdasd' (length=6)
'cod_postal' => string '051768' (length=6)
'recaptcha_challenge_field' => string '03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M' (length=249)
'recaptcha_response_field' => string '168' (length=3)
First I want to wrap the entire string replacing "" with [] :
[[\"form\",\"form-elements\"], [\"company\",\"asdasd\"], [\"cod_postal\",\"051768\"], [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"], [\"recaptcha_response_field\",\"168\"]]
And exclude [\"form\",\"form-elements\"] , [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"] and [\"recaptcha_response_field\",\"168\"]
What I can use to do that and how ?
You must filter the input. After filtering it you just return the json encoded string:
function arrayDisplay($input)
{
$input = array_filter($input, function ($key) {
return !in_array($key, array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
}, ARRAY_FILTER_USE_KEY);
return json_encode(array($input));
}
If you still want to return the key-value pairs separated by comma then keep the original implode function and concatenate the result with the squared brackets:
function arrayDisplay($input)
{
$input = array_filter($input, function ($key) {
return !in_array($key, array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
}, ARRAY_FILTER_USE_KEY);
return '[' . implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$input,
array_keys($input)
)
) . ']';
}
Please note that $xml_encode = json_encode($xml_array); makes no sense as the returned string is "almost" a valid json encoded string (in the original function). If this is your intention then you must use the first function I wrote and remove that line of code that is encoding again the returned value.
You should start from your $_POST array, and take the keys from it you really need:
$input = $_POST;
unset($input["form"]);
unset($input["recaptcha_challenge_field"]);
unset($input["recaptcha_response_field"]);
Now that $input array looks like this:
array(
"company" => "asdasd",
"cod_postal" => "051768"
);
Then, I would change the definition of your arrayDisplay function without altering its functionality, by splitting it into 2:
function arrayPairs($input) {
return array_map(
function ($v, $k) {
return [$k,$v];
},
$input,
array_keys($input)
);
}
function arrayDisplay($input) {
return implode (", ", array_map('json_encode', arrayPairs($input)));
}
This arrayDisplay function still returns the same values as before, but you can now also call arrayPairs without conversion to string. Instead you would do that conversion with json_encode which gives exactly the output you want:
echo json_encode(arrayPairs($input));
This outputs:
[["company","asdasd"],["cod_postal","051768"]]
NB: If you don't use the arrayDisplay function for any other purpose, then you can do away with it. This solution only uses the function arrayPairs.
I made some changes and ended up with this:
function arrayDisplay($input)
{
$goodKeys = array_diff(array_keys($input), array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
var_dump($goodKeys);
$data = [];
foreach ($goodKeys as $goodKey) {
$data[$goodKey] = $input[$goodKey];
}
return '[' . implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$data,
array_keys($data)
)
) . ']';
}
but now there is one more problem, I need to get rid of "" this 2 from the start/end of the string:
from this:
"[[\"company\",\"123\"], [\"cod_postal\",\"051768\"]]"
to this:
[[\"company\",\"123\"], [\"cod_postal\",\"051768\"]]

search and replace value in PHP array

I was looking for some standard PHP function to replace some value of an array with other, but surprisingly I haven't found any, so I have to write my own:
function array_replace_value(&$ar, $value, $replacement)
{
if (($key = array_search($ar, $value)) !== FALSE) {
$ar[$key] = $replacement;
}
}
But I still wonder - for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?
Note that this function will only do one replacement. I'm looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.
Instead of a function that only replaces occurrences of one value in an array, there's the more general array_map:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
To replace multiple occurrences of multiple values using array of value => replacement:
array_map(function ($v) use ($replacement) {
return isset($replacement[$v]) ? $replacement[$v] : $v;
}, $arr);
To replace a single occurrence of one value, you'd use array_search as you do. Because the implementation is so short, there isn't much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn't make sense for you to create such a function, if you find yourself needing it often.
While there isn't one function equivalent to the sample code, you can use array_keys (with the optional search value parameter), array_fill and array_replace to achieve the same thing:
EDIT by Tomas: the code was not working, corrected it:
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
Try this function.
public function recursive_array_replace ($find, $replace, $array) {
if (!is_array($array)) {
return str_replace($find, $replace, $array);
}
$newArray = [];
foreach ($array as $key => $value) {
$newArray[$key] = recursive_array_replace($find, $replace, $value);
}
return $newArray;
}
Cheers!
$ar[array_search('green', $ar)] = 'value';
Depending whether it's the value, the key or both you want to find and replace on you could do something like this:
$array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );
I'm not saying this is the most efficient or elegant, but nice and simple.
What about array_walk() with callback?
$array = ['*pasta', 'cola', 'pizza'];
$search = '*';
$replace = '\*';
array_walk($array,
function (&$v) use ($search, $replace){
$v = str_replace($search, $replace, $v);
}
);
print_r($array);
Based on Deept Raghav's answer, I created the follow solution that does regular expression search.
$arr = [
'Array Element 1',
'Array Element 2',
'Replace Me',
'Array Element 4',
];
$arr = array_replace(
$arr,
array_fill_keys(
array_keys(
preg_grep('/^Replace/', $arr)
),
'Array Element 3'
)
);
echo '<pre>', var_export($arr), '</pre>';
PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt
PHP 8, a strict version to replace one string value with another:
array_map(fn (string $value): string => $value === $find ? $replace : $value, $array);
An example - replace value foo with bar:
array_map(fn (string $value): string => $value === 'foo' ? 'bar' : $value, $array);
You can make full string matches without specifying the keys of qualifying values, by calling preg_replace() with a pattern containing start and end of string anchors (^, $). If your search term may contain characters which have a special meaning to the regex engine, then be sure to escape them with preg_quote() to avoid breakage. While regex is not entirely called for, regex offers some very convenient ways to tweak the search term handling. (Demo)
function array_replace_value(&$ar, $value, $replacement)
{
$ar = preg_replace(
'/^' . preg_quote($value, '/') . '$/',
$replacement,
$ar
);
}
I might be more inclined to use array_map() with arrow function syntax so that global variables can be accessed within the custom function scope. (Demo)
$needle = 'foo';
$newValue = 'bar';
var_export(
array_map(fn($v) => $v === $needle ? $newValue : $v, $array)
);
$ar = array(1,2,3,4,5,6,7,8);
$find = array(2,3);
$replace = array(13);
function update_bundle_package($ar,$find,$replace){
foreach ($find as $x => $y) {
///TO REMOVE PACKAGE
if (($key = array_search($y, $ar)) !== false) {
unset($ar[$key]);
}
///TO REMOVE PACKAGE
}
$ar = array_merge($ar, $replace);
}
<b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'
$input[$green_key] = 'apple'; // replace 'green' with 'apple'

Categories