Is it possible to use array_map in conjunction with str_replace without calling another function to do the str_replace?
For example:
array_map(str_replace(' ', '-', XXXXX), $myArr);
There is no need for array_map. From the docs: "If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well."
No, it's not possible. Though, if you are using PHP 5.3, you can do something like this:
$data = array('foo bar baz');
$data = array_map(function($value) { return str_replace('bar', 'xxx', $value); }, $data);
print_r($data);
Output:
Array
(
[0] => foo xxx baz
)
Sure it's possible, you just have to give array_map() the correct input for the callback function.
array_map(
'str_replace', // callback function (str_replace)
array_fill(0, $num, ' '), // first argument ($search)
array_fill(0, $num, '-'), // second argument ($replace)
$myArr // third argument ($subject)
);
But for the particular example in the question, as chiborg said, there is no need. str_replace() will happily work on an array of strings.
str_replace(' ', '-', $myArr);
Might be important to note that if the array being used in str_replace is multi-dimensional, str_replace won't work.
Though this doesn't directly answer the question of using array_map w/out calling an extra function, this function may still be useful in place of str_replace in array_map's first parameter if deciding that you need to use array_map and string replacement on multi-dimensional arrays. It behaves the same as using str_replace:
function md_str_replace($find, $replace, $array) {
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
$newArray = array();
foreach ($array as $key => $value) {
$newArray[$key] = md_str_replace($find, $replace, $value);
}
return $newArray;
}
Related
How can i trim with array of string in php. If I have an dynamic array as follows :
$arr = array(' ','<?php','?>',"'",'"');
so how can i use this array in trim() to remove those string, I tried very hard in the code below :
$text = trim(trim(trim(trim(trim($text),'<?php'),'?>'),'"'),"'");
but i can not use this because array is dynamic, it may have more than 1000 values.
It takes a lot of time to turn into a loop even after trying it.So I can do anything as follows
$text = trim($text, array(' ','<?php','?>',"'",'"') );
It's possible to apply trim() function to an array. The question seems to be unclear but you can use array_map(). Unclear because there are other enough possible solutions to replace substrings. To just apply trim() function to an array, use the following code.
$array = array(); //Your array
$trimmed_array = array_map('trim', $array); //Your trimmed array is here
If you also want to fulfill the argument requirement in trim() you can apply a custom anonymous function to array_map() like this:
$array = array(); //Your array
$trimmed_array = array_map(function($item){
return trim($item, 'characters to be stripped');
}, $array); //Your trimmed array is here
I'm using array_map to trim all my array values but I need to pass a third parameter because I need to more than just trim whitespaces so I'm passing in a third parameter. Basically I want to trim all array values of whitespaces, single quotes, and double quotes.
I have a utility class where I created the function and it looks like this:
public function convertToArray($string, $trim = false) {
$split = explode(",", $string);
if($trim) {
$split = array_map("trim", $split, array(" '\""));
}
return $split;
}
Somehow I can't make this work though. I can still see double quotes in the result even though I followed the answer here.
I even tried
if($trim) {
$split = array_map("trim", $split);
$split = array_map("trim", $split, array("'"));
$split = array_map("trim", $split, array('"'));
}
but I still get the same result.
array_map takes a function that takes only one parameter. If you want to map your array with trim() with subsequent parameters different from the default ones, you have to wrap it with an anonymous function:
$split = array_map(function($item) {
return trim($item, ' \'"');
}, $split);
I think you would need to use an anonymous function for that :)
$split = array_map(function ($value) {
return trim($value, " '\"");
}, $split);
Just because this was exactly the same as the other answer, here is an alternative. This approach could be useful if this is an operation you're going to need in many different places ;)
function trim_spaces_and_quotes($value) {
return trim($value, " '\"");
}
$split = array_map('trim_spaces_and_quotes', $split);
I'd use array_walk, and you just have to append your additional characters to the existing defaults (from the docs):
array_walk($string_arr_to_trim, function (&$v) {
$v = trim($v, " \t\n\r\0\x0B'\"");
});
I have an array..let say:
$array = [$a,$b,$c,$d];
How I can remove [ and ]?
The expected result would be:
$a,$b,$c,$d
I used some array function e.g array_slice but it does not fill my requirement. Any ideas?
Note: I need to pass all array elements to function as argument.
e.g: function example($a,$b,$c)
it sounds like you're after a string representation of the array, try using join() or implode() like this:
<?php
$array = [$a,$b,$c,$d];
$str = join(",", $array); // OR $str = implode(",", $array);
echo $str;
EDIT
after reading your question a little more carefully, you're trying to pass the array into a function call, to do that you need to use call_user_func_array():
<?php
function function_name($p1, $p2, $p3, $p4){
//do something here
}
$array = [$a,$b,$c,$d];
call_user_func_array('function_name', $array);
I've been using the recurisve SpinTax processor as seen here, and it works just fine for smaller strings. However, it begins to run out of memory when the string goes beyond 20KB, and it's becoming a problem.
If I have a string like this:
{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!
and I want to have random combinations of the words put together, and not use the technique as seen in the link above (recursing through the string until there are no more words in curly-braces), how should I do it?
I was thinking about something like this:
$array = explode(' ', $string);
foreach ($array as $k=>$v) {
if ($v[0] == '{') {
$n_array = explode('|', $v);
$array[$k] = str_replace(array('{', '}'), '', $n_array[array_rand($n_array)]);
}
}
echo implode(' ', $array);
But it falls apart when there are spaces in-between the options for the spintax. RegEx seems to be the solution here, but I have no idea how to implement it and have much more efficient performance.
Thanks!
You could create a function that uses a callback within to determine which variant of the many potentials will be created and returned:
// Pass in the string you'd for which you'd like a random output
function random ($str) {
// Returns random values found between { this | and }
return preg_replace_callback("/{(.*?)}/", function ($match) {
// Splits 'foo|bar' strings into an array
$words = explode("|", $match[1]);
// Grabs a random array entry and returns it
return $words[array_rand($words)];
// The input string, which you provide when calling this func
}, $str);
}
random("{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!");
random("{This|That} is so {awesome|crazy|stupid}!");
random("{StackOverflow|StackExchange} solves all of my {problems|issues}.");
You can use preg_replace_callback() to specify a replacement function.
$str = "{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!";
$replacement = function ($matches) {
$array = explode("|", $matches[1]);
return $array[array_rand($array)];
};
$str = preg_replace_callback("/\{([^}]+)\}/", $replacement, $str);
var_dump($str);
Is there a quick way ( existing method) Concatenate array element into string with ',' as the separator? Specifically I am looking for a single line of method replacing the following routine:
//given ('a','b','c'), it will return 'a,b,c'
private static function ConstructArrayConcantenate($groupViewID)
{
$groupIDStr='';
foreach ($groupViewID as $key=>$value) {
$groupIDStr=$groupIDStr.$value;
if($key!=count($groupViewID)-1)
$groupIDStr=$groupIDStr.',';
}
return $groupIDStr;
}
This is exactly what the PHP implode() function is for.
Try
$groupIDStr = implode(',', $groupViewID);
You want implode:
implode(',', $array);
http://us2.php.net/implode
implode()
$a = array('a','b','c');
echo implode(",", $a); // a,b,c
$arr = array('a','b','c');
$str = join(',',$arr);
join is an alias for implode, however I prefer it as it makes more sense to those from a Java or Perl background (and others).
implode() function is the best way to do this. Additionally for the shake of related topic, you can use explode() function for making an array from a text like the following:
$text = '18:09:00';
$t_array = explode(':', $text);
You can use implode() even with empty delimeter: implode(' ', $value); pretty convenient.