preg_replace, preg_replace_callback and Array to string conversion - php

I have this code from an app in PHP 5.4 :
$rightKey = preg_replace(array(
"/(_)(\p{L}{1})/eu",
"/(^\p{Ll}{1})/eu"
), array(
"mb_strtoupper('\\2', 'UTF-8')",
"mb_strtoupper('\\1', 'UTF-8')"
), $key);
It didn't work well, because preg_replace is deprecated. I did some researches and turned it into :
$rightKey = preg_replace_callback(array(
"/(_)(\p{L}{1})/u",
"/(^\p{Ll}{1})/u"
), function($m) { return array(
"mb_strtoupper('\\2', 'UTF-8')",
"mb_strtoupper('\\1', 'UTF-8')"
); }, $key);
I changed the function to preg_replace_callback, I removed the "e", and I added a callback.
But now I have :
Array to string conversion
And, I really don't know how to adapt the callback so it works ^^.
Thanks :),

The function must return a string, not an array, it is the same function for every matches:
$key = 'abc _def';
$rightKey = preg_replace_callback(array(
"/_(\p{L})/u",
"/(^\p{Ll})/u"
),
function($m) {
return mb_strtoupper($m[1], 'UTF-8');
},
$key);
echo $rightKey;
Output:
Abc Def

Related

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\"]]

preg_replace() digits to an array item

I've got this array:
<?php
$menu = array(
9 => 'pages/contact/',
10 => 'pages/calender/jan/'
//...
);
?>
And I've got a string that looks like this:
$string = "This is a text with a link inside it.";
I want to replace ###9### with pages/contact/.
I've got this:
$string = preg_replace("/###[0-9]+###/", "???", $string);
But I can't use $menu[\\\1]. Any help is appreciated.
There is a solution with preg_replace_callback but you can build an array where searched strings are associated to their replacement strings and then use strtr:
$menu = array(
9 => 'pages/contact/',
10 => 'pages/calender/jan/'
.... );
$keys = array_map(function ($i) { return "###$i###"; }, array_keys($menu));
$rep = array_combine($keys, $menu);
$result = strtr($string, $rep);
For this you need preg_replace_callback(), where you can apply a callback function fore each match, e.g.
$string = preg_replace_callback("/###(\d+)###/", function($m)use($menu){
if(isset($menu[$m[1]]))
return $menu[$m[1]];
return "default";
}, $string);

php replacement route system

i need function in PHP for handle replacement something like this.
$pattern = ':foo/anotherString';
$replacement = array(
'foo' => 'HelloMe'
);
bazFunction($pattern, $replacement); // return 'HelloMe/anotherString';
this method used in some frameworks as route patterns. i want to know which function handle that.
this should do (5.3 required because of the closure)
function my_replace($pattern, $replacement) {
// add ':' prefix to every key
$keys = array_map(function($element) {
return ':' . $element;
}, array_keys($replacement));
return str_replace($keys, array_values($replacement), $pattern);
}
You wouldn't need this function if you pass the stuff directly to str_replace
str_replace(array(':foo'), array('HelloMe'), ':foo/anotherString');
$string = "foo/anotherString";
$replacement = array('foo','HelloMe');
$newString = str_replace($replacement[],,$string);
It seems that php got the function for you...
str_replace ( ":foo", "HelloMe" , $pattern )
will give you this output: HelloMe/anotherString

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'

Replace string in an array with 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);

Categories