Replace multiple values in a variable - php

I'm looking forward a solution to replace multiple values from one of my variable ($type)
This variable can have 34 values (strings).
I would like to find a way to create a new variable ($newtype) containing new strings from the replacement of my $type.
I think using str replace would be a good solution, but the only way I see things is creating a big "If ..." (34 times?) but does not seem the best way..
Thanks in advance for you help.
Best regards.

I would advise against storing a string on multiple values in a variable as it will just get messy!
Store variables in an array in the following way
$type['value1'] = 'cheese';
$type['value2'] = 'ham';
Then if you need to change it you can just do
$type['value2'] = 'chicken';
and you will get (if using print_r)
Array
(
[value1] => cheese
[value2] => chicken
}
This means all your values will be neatly stored next to a relevant key and be easily accessable as part of an individual request
echo $type['value1']
which will echo out
Cheese

You can use preg_replace with arrays:
$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2';
$to[2]='to3';
$newtype=preg_replace($from, $to, $type);
I have never used it like this but the documentation says that you need to use ksort to correctly match the order of the replaces:
$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2';
$to[2]='to3';
ksort($to);
ksort($from);
$newtype=preg_replace($from, $to, $type);

Related

Is there a simple way to return WHAT is similar between 2 strings in PHP?

I've looked into the similar_text() and levenshtein() functions, but they only seem to return THAT there are similarities and the percentage of those similarities.
What I am trying to do is compare 2 strings to determine WHAT is actually similar between the two.
Basically:
<?php
$string1 = "IMG_1";
$string2 = "IMG_2";
echo CompareTheseStrings($string1,$string2); // returns "IMG_";
If this wonderful function doesn't exist, what would be the best way to accomplish this?
My end game plan is to read through a list of file names and then replace the similar text with something user defined or just remove it all together, but I don't want to replace each files unique identifier.
Reading your 'end goal' I think you're going about this completely the wrong way I think you should really be looking at str_replace
$string1 = "IMG_1";
$string2 = "IMG_2";
// you would create a loop here to insert each string
str_replace("IMG", "NEW_TERM", $string1);
If you want to remove the text altogether then just pass an empty string in as the 2nd parameter

How to split a search url into an associative array

So I would like to take a string like this,
q=Sugar Beet&qf=vegetables&range=time:[34-40]
and break it up into separate pieces that can be put into an associative array and sent to a Solr Server.
I want it to look like this
['q'] => ['Sugar Beets],
['qf'] => ['vegetables']
After using urlencode I get
q%3DSugar+Beet%26qf%3Dvegetables%26range%3Dtime%3A%5B34-40%5D
Now I was thinking I would make two separate arrays that would use preg_split() and take the information between the & and the = sign or the = and the & sign, but this leaves the problem of the final and first because they do not start with an & or end in an &.
After this, the plan was to take the two array and combine them with array_combine().
So, how could I do a preg_split that addresses the problem of the first and final entry of the string? Is this way of doing it going to be too demanding on the server? Thank you for any help.
PS: I am using Drupal ApacheSolr to do this, which is why I need to split these up. They need to be sent to an object that is going to build q and qf differently for instance.
You don't need a regular expression to parse query strings. PHP already has a built-in function that does exactly this. Use parse_str():
$str = 'q=Sugar Beet&qf=vegetables&range=time:[34-40]';
parse_str($str, $params);
print_r($params);
Produces the output:
Array
(
[q] => Sugar Beet
[qf] => vegetables
[range] => time:[34-40]
)
You could use the parse_url() function/.
also:
parse_str($_SERVER['QUERY_STRING'], $params);

Modification in $_REQUEST response or any alternative to get correct value in array using explode

In my application there are different promotions and usera can answer to that promotions using single or multi choice questions. I am using following logic and it works fine except one problem:
for ($i=0;$i<count($questions);$i++)
{
if($questions[$i][type_of_question] == 'multiple_choice')
{
$options_array = explode(",", $_REQUEST["que".$questions[$i][id]]);
}
// Code here which insert answers in database table
}
This line of code:
$options_array = explode(",", $_REQUEST["que".$questions[$i][id]]);
this code shows comma seperated answers of the questions. For example:
Example 1: test1,test2,test3 [This scenario works fine]
Example 2: yes,no,I am not interested(cricket,footbal)
Example 2 has shows the problem e.g. if there is , inside the choice option. Php explode function break and values according to , so in this case I gets 4 array elements.
Array[0] => yes
Array[1] => no
Array[3] => I am not interested(cricket
Array[4] => footbal
while I required following:
Array[0] => yes
Array[1] => no
Array[3] => I am not interested(cricket,footbal)
How can I fix this problem? Any suggestion?
You need to fix the way the data is being fed in from the front-end: there's no way in this code alone to fix this problem. For example, you could have the input yes, no, maybe, and it could be either yes, no, maybe, or yes, no, maybe.
You need to perform some consistent encoding or escaping on the front-end so you can uniquely access the records. You haven't told us how it's submitted on the front, but just joining the answers together with commas won't be enough. You could try escaping the commas in the fields!

splitting a string every 4 characters and then put those into new variables?

How would i split a string every 4 characters and then have every 4 characters put into a separate variable so i can do other stuff with each individual 4 characters?
Well, I don't really see you putting each of them in a different variable, because then you'll have like 10 variables:
$var1 = ...;
$var2 = ...;
$var3 = ...;
But you could use the str_split function as following:
$variable = str_split($origionalvar, 4);
it will create an array, which you can access:
$variable[0] to $variable[sizeof(variable)]
If you don't know about arrays, you really should read up on those. They are really great if you want to store a lot of similar information in an object and you don't want to create a new variable for it every time. Also you can loop over them very easily and do some other great stuff with them.
I assume you probably googled this question a bit too. You must have come across http://php.net/manual/en/function.str-split.php. Did you see this page, and if you did, did you have some trouble with it. If so perhaps we can help you reading the documentation properly.
Have a look at the str_split function. The PHP manual will tell you all you need to know.

Declaring static arrays in php

I am new to php. I was wondering how I could declare a static array in php. Here is what I would do in C. How is the corresponding php code for it?
char a[][] = { (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3) };
From what I read it has to be something like this -
$a = array( 1 => array(1,1), 2 => array(1,2), ... );
Is this correct? If so it sucks :) I hope I am wrong.
Thanks,
- Pav
You've already found the way to do it natively.
Another option would be to declare your data as JSON (a very concise and human-friendly format). This could be either in a separate file bundled with your app, or directly in your code in a string. Then parse the JSON at runtime. Since PHP isn't exactly known for speed, this may or may not make your noticeably app slower to start.
you have it already figured out in your question.
One thing I would add is that you do not need to explicitly define the keys if you are intending to use a zero based array, this is assumed and can be done like so...
$a = array(array(1,1),array(1,2), ... );
You can also use what is called associative arrays which use string keys and you define them the same way you do in your example, except use strings instead of numbers...
$ass_array = array( 'array_1' => array(1,1), 'array_2' => array(1,2), ... );
you would then call your associative array like this...
$ass_array['array_1'];
Also, if you want to append single items to an array (for example in a loop to load an array)...
$ass_array[] = $item;
Further to jondavidjohn's anwser, you could just write a quick script to grab your list of values and generate the array statement for you.
No need to care how verbose the syntax is then. If the task is long and repetitious enough to care, don't do it by hand. :)

Categories