PHP Mass String Replace - php

In PHP, I want to execute str_replace on multiple variables, efficiently, when all variables shall abide by the same str_replace values.
Bascially, I am expecting to see the following:
$var1=str_replace("0.00","\$0",$var1);
$var2=str_replace("0.00","\$0",$var2);
$var3=str_replace("0.00","\$0",$var3);
$var4=str_replace("0.00","\$0",$var4);
...
this is repetitive and especially annoying when adding more variables to such replace. I have constructed the following loop
foreach ( array("var1","var2","var3","var4") as $variablename ) {
${$variablename} = str_replace("0.00","\$0",${$variablename});
}
This loop works (for those of you viewing this page looking for such an example) , however, I am not convinced that this is the most efficient way (assuming mass replacing)
Any thoughts?

The third parameter of str_replace can accept an array of variables to perform the replace on. It should be better performing that any custom loop.
$results = str_replace("0.00","\$0", array($var1, $var2, $var3));

Related

Stringing together variables, str_replace. Tidier way to do this?

I have a bunch of variables that I want to string together. They all need to be tidied up by removing spaces and commas, and converting to dashes (I'm constructing a URL).
I have a very basic understanding of PHP, but I feel my code below could be tidier and more efficient. Could you point me to some resources or make some suggestions please?
Here's what I have:
$propNum = $prop->Address->Number;
$propStreet = $prop->Address->Street;
$propTown = $prop->Address->Town;
$propPost = $prop->Address->Postcode;
$propFullAdd = array($propNum, $propStreet, $propTown, $propPost);
$propFullAddImp = implode(" ",$propFullAdd);
$propFullAddTidy = str_replace(str_split(' ,'),'-', strtolower($propFullAddImp));
echo $propFullAddTidy;
From the output of your existing code, it seems like you may want an output that looks something like:
12345-example-street-address-example-town-example-postcode
In this case, you could use this solution:
//loop through all the values of $prop->Address
foreach($prop->Address as $value) {
//for each value, replace commas & space with dash
//store altered value in new array `$final_prop`
$final_prop[] = str_replace([' ', ','], '-', $value);
/*
Removing `str_split(' ,')` and subbing an array makes the loop "cheaper" to do,
Because the loop doesn't have to call the `str_split()` function on every iteration.
*/
}
//implode `$final_prop` array to dash separated string
//also lowercase entire string at once (cheaper than doing it in the loop)
$final_prop = strtolower(implode('-', $final_prop));
echo $final_prop;
if you remove the comments, this solution is only 4 lines (instead of 7), and is completely dynamic. This means if you add more values to $prop->Address, you don't have to change anything in this code.
A different method
I feel like this would usually be handled by using http_build_query(), which converts an array into a proper URL-encoded query string. This means that each value in the array would be passed as it's own variable in the URL query.
First, $propFullAdd is not necessary (in fact, it may be detrimental), $prop->Address already contains the exact same array. Recreating the array like this completely removes the ability to tell which value goes to which key, which could be problematic.
This means that you can simplify your entire code by replacing it with this:
echo http_build_query($prop->Address);
Which outputs something like this:
Number=12345&Street=Example+Street+Address&Town=Example+Town&Postcode=Example+Postcode

How to set array's two keys with same value? (PHP)

There exists such:
$var1 = $var2 = "blabla";
but is there a way to set similar inside array? like:
array(
'key1'='key2' => "blabla",
...................
)
p.s. I dont need outside of array functions, like array_fill_keys or etc.. I want inside-array solution (if it exists).
You can set multiple array values of an array like this. Perhaps it even works without the first line.
$a = array();
$a['key1'] = $a['key2'] = 'blablabla';
Or initialize the desired keys using this awkward syntax:
$a = array_fill_keys(array('key1', 'key2'), 'blablabla');
Although the second one works, I wouldn't use it. Better to use a couple of characters extra or even separate lines than to write such a weird line which doesn't have much benefit apart from saving a tiny bit of code.

Passing an array of variable length to a class method

I am trying to create a little MVC framework for myself and am using a url structure similar to: http://www.example.com/className/methodName/var1/var2/var3. I want to make it able to accomodate for any number of variables.
I have all of the information how I need it, except for the /var1/var2/var3 part. Currently I have it in an array exploded() upon the "/", so: var[0] = "var1",var[1] = "var2",var[2] = "var3"
Since the method which will be called will be unknown and each method can require a different amount parameters I want to figure out a way to be able to pass the parameters as:
$controller->$function($var1, $var2, $var3);
rather than
$controller->$function($var);
I realize I can string together a comma delimited variable such as $var1, $var2, $var3 and use eval() to do what I want, but I am wondering if there is a better way to go about it. I would rather not use eval() for this as it will be using user submitted data.
Worst case scenario, I figure I would just try to cleanse the data before the eval, but I'd still like to avoid it.
One other potential Idea I had was to use a foreach() and loop through each element inside of the the method call. But even that seems a little messy to me.
On a side note, is the standard way to pass a variable amount of parameters to group them together in an array and pass in a single parameter?
If anyone knows of a more elegant way to do this, I would really appreciate it.
Use call_user_func_array
call_user_func_array(array($controller, $function), array($var1, $var2...));
#Dogbert's answer would complement what I'm about to suggest.
You could create a function that accepts no parameters and you're free to pass as many parameters (or no parameters at all), you'll only have to use PHP functions like: func_get_args(), func_num_args() and func_get_arg(int arg_index) to do your manipulation.
An Example follows below:
function syncOrderRelation(){
$num_arguments = func_num_args();
$arguments = func_get_args();
#gets all the arguments in the request
list($userID,$spID,$productID) = $arguments;
#if you know what you're expecting or
for($i = 0; $i < $num_arguments; $i++){
$argument_at_index = func_get_arg($i);
}
}
You could call this function in the following ways:
syncOrderRelation();
syncOrderRelation($var1,$var2,var3);
syncOrderRelation($var1);
#or you could call it as #Dogbert suggested since the function will accept whatever
#arguments you supply
The rest is up to you...Happy coding!

Find and concatenate result in a pattern

I have a long PHP file and I want to copy all the variable names only and build an insert sql query. Is there a way where I can search for a pattern using regular expression and concatenate the find result till I collected all the variable and spit it out in a statement?
I am using TextMate and am familiar with regular expression search. Regex search result give $0,$1 and so forth argument. Do not know if this possible though. Solution in any editor will do not just text mate.
I have just too many variable (+100) don't feel like copy every single one. Here my sample file
$ID = $_POST['id'];
$TXN_TYPE = $_POST['txn_type'];
$CHARSET = $_POST['charset']
$CUSTOM = $_POST['custom'];
You could try something with get_defined_vars(). However this function also lists GLOBAL vars. You can use this snippet to remove them if you don't want them and display only the vars you defined
$variables = array_diff(get_defined_vars(), array(array()));
However this snippet generates Notices and I haven't found a way to solve them yet.
If you've only got $_POST variables you can loop through the $_POST array itself
You create the SQL programmatically while looping through the array.
My own solution is, do the inverse. It is not probably possible.
Leave only the variable names Remove all the rest. Use
[space].+ regex to remove everything that is after the variable name.
clean the file so that only variable names are left. then do a couple more find and replace to bring the variable name in the form you want.
If you're looking to match only the variable names (not the $_POST array indices), then the regular expression is pretty much provided in the PHP documentation:
\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
This will, of course, include $_POST, but that should be easy enough to remove. If not, you could do it with negative lookahead (if TextMate supports it):
\$(?!_POST($|[^a-zA-Z0-9_\x7f-\xff]))[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

remove duplicate from string in PHP

I am looking for the fastest way to remove duplicate values in a string separated by commas.
So my string looks like this;
$str = 'one,two,one,five,seven,bag,tea';
I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?
The shortest code would be:
$str = implode(',',array_unique(explode(',', $str)));
If it is the fastest... I don't know, it is probably faster then looping explicitly.
Reference: implode, array_unique, explode
Dealing with: $string = 'one,two,one,five,seven,bag,tea';
If you are generating the string at any point "up script", then you should be eliminating duplicates as they occur.
Let's say you are using concatenation to generate your string like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').some_func($value);
}
...then you would need to extract unique values from $string based on the delimiter (comma), then re-implode with the delimiter.
I suggest that you design a more direct method and deny duplicates inside of the initial foreach loop, like this:
foreach($data as $value){
$return_value=some_func($value); // cache the returned value so you don't call the function twice
$array[$return_value]=$return_value; // store the return value in a temporary array using the function's return value as both the key and value in the array.
}
$string=implode(',',$array); // clean: no duplicates, no trailing commas
This works because duplicate values are never permitted to exist. All subsequent occurrences will be used to overwrite the earlier occurrence. This function-less filter works because arrays may not have two identical keys in the same array(level).
Alternatively, you can avoid "overwriting" array data in the loop, by calling if(!isset($array[$return_value])){$array[$return_value]=$return_value;} but the difference means calling the isset() function on every iteration. The advantage of using these associative key assignments is that the process avoids using in_array() which is slower than isset().
All that said, if you are extracting a column of data from a 2-dimensional array like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').$value['word'];
}
Then you could leverage the magic of array_column() without a loop like this:
echo implode(',',array_column($str,'word','word'));
And finally, for those interested in micro-optimization, I'll note that the single call of array_unique() is actually slower than a few two-function methods. Read here for more details.
The bottomline is, there are many ways to perform this task. explode->unique->implode may be the most concise method in some cases if you aren't generating the delimited string, but it is not likely to be the most direct or fastest method. Choose for yourself what is best for your task.

Categories