Trim doesn't seem to work PHP - php

I'm a fan of the function trim in PHP. However, I think I've run into a weird snag. I have the string named keys that contains: "mavrick, ball, bouncing, food, easy mac, " and execute this function
// note the double space before "bouncing"
$keys = "mavrick, ball, bouncing, food, easy mac, ";
$theKeywords = explode(", ", $keys);
foreach($theKeywords as $key){
$key = trim($key);
}
echo $theKeywords[2];
However here, the output is " bouncing" not "bouncing". Isn't trim the right function to use here?
edit:
My original string has two spaces before "bounce", for some reason it didn't want to show up.
And I tried referencing it with foreach($theKeywords as &$key) but it threw an error.

The problem is that you work with a copy and not the original value. Use references instead:
$theKeywords = explode(", ", $keys);
foreach($theKeywords as &$key){
$key = trim($key);
}
echo $theKeywords[2];

You're not re-writing the values in the original array in your loop, you could simplify this to one line, using array_map, like so
$theKeywords = array_map('trim', explode(',', $keys));

$key gets a copy of the value, not the actual value. To update the actual value, modify it in the array itself (for example, by using a for loop):
$theKeywords = explode(", ", $keys);
for($i = 0; $i < count($theKeywords); $i++) {
$theKeywords[$i] = trim($theKeywords[$i]);
}
echo $theKeywords[2];

Another way using a closure:
$keys = "mavrick, ball, bouncing, food, easy mac, ";
$theKeywords = explode(", ", $keys);
array_walk($theKeywords, function (&$item, $key) {
$item = trim($item);
});
print $theKeywords[2];
But, it will only work in PHP 5.3+

Related

Replacing ',' characters in only odd positions

I need replace ',' characters with regex in php, but only in odd positions
I have:
{"phone","11975365654","name","John Doe","cpf","42076792864"}
I want replace ',' to ':', but only the odd:
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}
I'm trying this regex:
preg_replace('/,/', ':', $data)
But it get all quotes and no only the odd.
Can you help me?
Make it simple:
preg_replace('/(("[a-z]+"),(".+?"))+/', '$2:$3', $a)
Rather than regex, this just converts the list to an array (using str_getcsv() to cope with the quotes). Then loops every other item in the list, using that item as the key and the next item as the value. This can then be json_encoded() to give the result...
$data = str_getcsv(trim($input, "{}"));
$output = [];
for ( $i=0, $k=count($data); $i < $k; $i+=2) {
$output[$data[$i]] = $data[$i+1];
}
echo json_encode($output);
It is not ideal to use regex for this task. Having said that, if you know that your input can be matched by a simple regex, this should do it :
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$result = preg_replace('/,(.*?(?:,|[^,]*$))/ms', ':\\1', $str);
This lenient to some extra characters but it will fail if any string contains commas
Example
Here's an example of using standard PHP functions:
$input = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$dataIn = str_getcsv(trim($input, '{}'));
$keys = array_filter($dataIn, function ($key) { return !($key & 1); }, ARRAY_FILTER_USE_KEY);
$values = array_filter($dataIn, function ($key) { return $key & 1; }, ARRAY_FILTER_USE_KEY);
$DataOut = array_combine($keys, $values);
$output = json_encode($DataOut);
echo $output;
This code is a lot longer than using a regex, but it is probably easier to read and maintain in the long run. It can cope with commas in the values.
Another option could be using array_splice and loop while there are still elements in the array:
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$data = str_getcsv(trim($str, '{}'));
$result = array();
while(count($data)) {
list($k, $v) = array_splice($data, 0, 2);
$result[$k] = $v;
}
echo json_encode($result);
Output
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}

How to replace part of a multi array variable with a different variable?

Here is an example of what I am trying to accomplish:
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
echo $array['aaa']$subarray; // these 2 echos should be the same
echo $array['aaa']['bbb']['ccc']; // these 2 echos should be the same
It should display the same as $array['aaa']['bbb']['ccc'] i.e., "value".
This doesnt work, of course. But is there some simple solution to this?
There could be some function and the $subarrayvalue may be used as a parametr and/or as an array itself like: $subarray = array('bbb','ccc'); I dont mind as long as it worsk.
You could try something like below.
$subarray = "['bbb']['ccc']";
$temp = parse_str("\$array['aaa']".$subarray);
echo $temp;
OR To ignore single quotes -
$subarray = "[\'bbb\'][\'ccc\']";
$temp = parse_str("\$array[\'aaa\']".$subarray);
echo $temp;
Also you may refer - http://php.net/manual/en/function.parse-str.php
Just try using array chunk function http://php.net/manual/en/function.array-chunk.php
here is what actually works!!
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
$string = 'echo $array[\'aaa\']' . $subarray . ';';
eval($string);

php reading in strings from text area

$data = explode("\n", trim($_GET['names']));
while($i < count($data)) {
if(!in_array($data[$i], $unique_names)){
$unique_names[] = $names[$i];
}
$i = $i + 1;
}
I am trying to accept only unique results from a textarea using this php code. It is not working because every string has an extra blank space, except for the last one.
I.E.
"jeff "
"fred "
"bill "
"jeff"
so jeff will be added twice.
My question is:
How Do I get rid of that space?? I tried trim and it won't perform as intended.
First of all, you don't need to find unique values manually, you can use array_unique(). Secondly, trim() doesn't work on arrays.
Try:
$raw_names = explode("\n", $_GET['names']);
$trimmed_names = array_map('trim', $raw_names);
$unique_names = array_unique($trimmed_names);
Use trim(string) to remove whitespace from the start and end. http://php.net/manual/en/function.trim.php
Inspired by kba :
$data = explode("\n", trim($_GET['names']));
foreach ($data as &$e) {
$e = trim($e);
}
$unique_names = array_unique($data);

How to handle my data?

Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}

Array a string in the following format?

How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:
101=1&2020=2&303=3
(Incase your wondering, its the result of jQuery Sortable Serialize...
I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?
I just want to explode this in a way that $key = 101 and $value = 1
Sounds confusing ;)
Thanks so so much in advanced!!
See the parse_str function.
It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:
$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
One quick and dirty solution:
<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
list($key, $value) = each(explode('=', $pair));
$VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
$pair = explode("=",$e);
$output[$pair[0]] = $pair[1];
}
Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.

Categories