php reading in strings from text area - php

$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);

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"}

Compare string from input field with value in multidimension array

$klasseinput = strtoupper(trim($_POST["klasseliste"]));
$data = file('student.txt');
$data = array_filter($data);
foreach($data AS $row){
$student[] = explode(';', $row);
}
$antall = count($student);
for ($i = 0; $i < $antall; $i++){
if($klasseinput == $student[$i][3]){
print('<tr><td>'.$student[$i][0]."</td><td>".$student[$i][1]."</td><td>".$student[$i][2]."</td><td>".$student[$i][3]."</td></tr>");
}
}
/////////STUDENT.txt//////////
ph;petter;hanssen;IT1
gb;Geir;Bjarvin;IT2
mj;Marius;Johansen;IT3
/////////////////////////////
I am trying to compare an input form with an item in the multidimension array, but even tho the variable from the input field is exactly the same as the value in the array, it doesnt pass the if check.
$student[0][3] = IT1
$student[1][3] = IT2
$student[2][3] = IT3
If you have made sure there is no white space spoiling the comparison, then you might find a function like this useful to look at the strings on both sides of the comparison. You might find there are spurious characters causing trouble.
function hexdump($str)
{
for($i=0; $i<strlen($str);$i++)
{
echo "[$i] [".bin2hex($str[$i])."] [".$str[$i]."]<br />";
}
}
For instance, the string read from the file might contain CR LF characters. You could get rid of them using str_replace().
Thanks to Ravinder Reddy for the answer that was simple and worked for me:
" trim the value for \t\n if($klasseinput == trim($student[$i][3])){ "

Trim doesn't seem to work 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+

No Output? PHP foreach doesn't seem to work

I am trying to form an acronym from a given text. The Idea here is that the first Letter in $text ($text[0]) will be taken and placed inside the array $storage using array_push(). Now, if there is a space inside the array, the letter of the next index should be a part of the Acronym. I am currently not getting an ouput, what am I missing?
public function Acronym($text)
{
$text = str_split($text);
$count = strlen($text);
$storage = array();
for($i=0; $i<$count; $i++)
{
array_push($storage, $text[0]);
if($text[$i]==' ')
{
array_push($storage, $text[$i+1]);
}
foreach($storage as $clean)
{
echo $clean;
}
}
}
Your algorithm suffers from a few fatal flaws:
You're calling strlen() on an array, when you should be calling count():
$text = str_split($text);
$count = count($text);
However, you can index strings as arrays, so you don't need str_split() in this scenario, and you can keep $count = strlen( $text); by removing the call to str_split().
This should only happen once, so it should be outside the loop (This implies starting $i at 1):
array_push($storage, $text[0]);
Your foreach loop that prints the $storage array should be outside of the loop that is creating the acronym.
You can save the overhead of calling a function by using the shorthand array_push() notation. You should use array_push() when adding more than one element to an array. Otherwise, this will suffice:
$storage[] = $text[0];
You need to return something from your function, otherwise you won't be able to access anything outside of it.
Put that all together, and you get this:
public function Acronym($text)
{
$count = strlen( $text);
$storage[] = $text[0];
for( $i = 1; $i < $count; $i++)
{
if( $text[$i] == ' ')
{
$storage[] = $text[$i+1]);
$i++; // Can increment $i here because we know the next character isn't a space
}
}
foreach($storage as $clean)
{
echo $clean;
}
return $storage;
}
That being said, there are far better implementations for forming an acronym giving a string input. Here is one that I can think of:
public function Acronym( $text)
{
$acronym = array();
foreach( explode( ' ', $text) as $word)
{
$word = trim( $word);
$acronym[] = strtoupper( $word[0]);
}
return implode( '', $acronym);
}
Note that both functions will fail for inputs like Hello World. I am leaving it up to the OP to make these modifications (if necessary).
str_split turns the string into an array.
str_length brings the length of a string which you have overwritten with an array already. you need count()
You overwrite your first variable $text
$count = strlen($text);
In this line $text is an array, because you changed it in the first line of your method.
Try inverting the two first lines:
$count = strlen($text);
$text = str_split($text);
Note
This will solve your secondary problem, and enable your algorithm to run without errors. It doesn't fix your algorithm, but at least you will be able to debug it now.
you are running your loop on $count which is getting its value from str_len its an array because of return on $text = str_split($text);
So you have overwritten your $text variable you can fix it by changing order get length first then split.

Take a part of a string (PHP)

We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?
That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);
Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];
$StringArray = explode ( ":" , $string)
By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);
it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);
the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

Categories