Populating an array with fields from a string - php

I have this string that contains the following quote-contained, comma-separated values:
"field","anotherfield","yetanotherfield"
I need to populate an array with the content of these fields, without the quotes.
What I'm currently doing is:
$string = str_replace('"', NULL, $string);
and then
$array = explode(',', $string);
It works, but it breaks when there's a comma inside any field. How can I prevent this?

first, trim " from the start and end of string.
$string = trim('"field","anotherfield","yetanotherfield","other, another"', '"');
and after explode "," between values you need.
$array = explode('","', $string);

To parse entire CSV file into an array you could use str_getcsv function:
$array = array_map( 'str_getcsv', file( 'path-to-file/file.csv' ) );

Related

str_replace by 2 array's created by sql

I already know how to use string replace by creating an array manually:
array('value1','value2','value3','value4');
But how do I use str_replace by values from a Database?
$original_string = (fruit_1+fruit_2+fruit_3);
table1 database values: fruit_1 fruit_2 fruit_3
table2 database values: 237 9388 2377
output what i want: (237+9388+2377)
The normal str_replace procedure i already know:
$replaced_string = str_replace($searchwords, $replacewords, $original_string );
How do i get all the values from the database and process them by str_replace?
Can this be done by creating an array or so?
I use PDO to get values from the database.
Thank you!!!
Martijn
str_replace can take array arguments as well, so you can do this:
$original_string = '(fruit_1+fruit_2+fruit_3)';
$find = explode(' ', 'fruit_1 fruit_2 fruit_3');
$replace = explode(' ', '237 9388 2377');
$new_string = str_replace($find, $replace, $original_string);
// gives (237+9388+2377)

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

Exploding string after removing whitespace

I am trying to process copied text from a website.
I am using iMacros to get the content from table and extracted data has lots of spaces between data.
I was trying trim and str_replace to remove spaces and it works but the problem I have is that when I am trying to explode new string, it looks like I am exploding original one, before trimming! Array has hundreds of keys!
What I am doing wrong?
Sample data:
"1","
Data1
","
Data2
","
Data3
","-","-1","-","-","-","-"
Here is a code that I'm using:
$data_lines = preg_split( '/\r\n|\r|\n/', $_POST['data'] );
foreach($data_lines as $data_line) {
$data_line = str_replace(' ', '', $data_line);
$data_line = str_replace('"', '', $data_line);
$data_line = explode(',', $data_line);
echo '<pre>';
print_r($data_line);
echo '</pre>';
}
So the goal is to get Data values and symbols/numbers in quotes (obviously whiteout the quotes) in array.
Thanks for help in advance
How about:
$data = explode(',', preg_replace(
array('/\r\n|\r|\n/', '/"\s*(\S*?)\s*"/'),
array('' , '$1' ),
$_POST['data']
));
working example
Use Trim function in php
trim — Strip whitespace (or other characters) from the beginning and end of a string - php.net
http://php.net/manual/en/function.trim.php

How do I place a comma between each character in a string with PHP? [duplicate]

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How to remove last comma (,) from array?

I've gone through this address:
Passing an array to a query using a WHERE clause
and found that if I use a join clause to separate values , is also at the end of the array. How can I remove last?
I am using like this
$ttst=array();
$ttst=array();
$tt = "SELECT frd_id FROM network WHERE mem_id='$userId'";
$appLdone = execute_query($tt, true, "select");
foreach($appLdone as $kk=>$applist){
$ttst[] = $applist['frd_id'];
}
$result = implode(',', $ttst);
then also coming last ,
Thanks.
but it doesn't give single quote to each value .
join(',', array_filter($galleries))
array_filter gets rid of empty elements that you seem to have. Of course, you should take care not to have empty elements in there in the first place.
You could use trim() (or rtrim()):
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
$str = "orange,banana,apple,";
$str = rtrim($str,',');
This will result in
$str = "orange,banana,apple";
Update
Based on your situation:
$result = implode(',', $ttst);
$result = rtrim($result,',');
$arr = array(...);
$last = end($arr);
unset($last);
If the trailing "," is an array element of itself, use array_pop(), else, use rtrim()
$array = array('one','two',3,',');
array_pop($array);
print_r($array);
Gives:
Array ( [0] => one 1 => two 2 => 3
)
No need for length. Just take from beginning to the (last character - 1)
$finalResult = $str = substr($result, 0, -1);
Use implode() instead! See Example #1 here http://php.net/manual/en/function.implode.php
Edit:
I think a quick fix would be (broken down in steps):
$temp = rtrim(implode(',', $ttst), ','); //trim last comma caused by last empty value
$temp2 = "'"; //starting quote
$temp2 .= str_replace(",", "','", $temp); //quotes around commas
$temp2 .= "'"; //ending quote
$result = $temp2; // = 'apples','bananas','oranges'
This should give you single-quote around the strings, but note that if some more values in the array are sometimes empty you will probably have to write a foreach loop and build the string.

Categories