I'm using a CSV script from phpclasses.org. It retrieves column names and column values from a table/more tables and creates a CSV.
There's one thing I don't understand.
Here's the piece of code I'm looking at:
function createcsv($tablename){
$rs = $this->SelectAll($tablename);
$rs1 = $this->SelectAll($tablename);
if($rs){
$string ="";
/// Get the field names
$fields = mysql_fetch_assoc($rs1);
if(!is_array($fields))
return;
while(list($key,$val) =each($fields)) {
$string .= $key.',';
}
$string = substr($string,0,-1)."\015\012"; //removes last and comma and adds a newline
/// Get the data
while($row = mysql_fetch_assoc($rs)) {
while(list($key,$val) =each($row)){
$row[$key] = strip_tags(html_entity_decode($row[$key])); //strips tangs from the html decoded value
$row[$key] = str_replace(',',' ',rtrim($row[$key])); //replaces commas with empty spaces from the trimmed value
$row[$key] = str_replace("\015\012",' ',$row[$key]);
}
$string .= (implode($row,","))."\015\012";
}
echo $string;
//$fp = fopen($this->path.$tablename.".csv",'w');
//fwrite($fp,$string);
//fclose($fp);
}
}
The 2 lines I'm wondering about are:
$row[$key] = str_replace(',',' ',rtrim($row[$key])); //replaces commas with empty spaces from the trimmed value
$row[$key] = str_replace("\015\012",' ',$row[$key]);
I thought rtrim removes new lines too (\n)... so why is the second line $row[$key] = str_replace("\015\012",' ',$row[$key]); used?
rtrim removes newlines from the end (r = "right") of the string. The line you quoted removes them anywhere in the string.
Looking at the page you kindly linked in your question, I can read
from the end of a string
so, I can conclude that it doesn't remove any new lines from whatever else part of the string.
Related
I would I am using PHP. I am reading from a file but I would like to eliminate the following characters from the file wherever they are: '' and { }.
I tried to use the trim function but the characters "',{ and }" are still present in the output:
$txt_file = file_get_contents('out.txt');
$rows = explode(",", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(':', $data);
trim($row,"'");
trim($row,"{");
trim($row,"}");
$info[$row]['state'] = $row_data[0];
$info[$row]['action'] = $row_data[1];
echo $info[$row]['state'] . '<br />';
echo $info[$row]['action'] . '<br />';
echo '<br />';
}
Do you have any idea how to do it?
Thanks
I assume you want to remove ' { and } from $row
If it is, then replace
trim($row,"'");
trim($row,"{");
trim($row,"}");
with
$row = str_replace(['\'', '{', '}'], '', $row);
Note: trim — Strip whitespace (or other characters) from the beginning and end of a string. Moreover you didn't store trimmed data to any variable so literally you will not get trimmed data. You want to replace characters wherever it is found so use str_replace or preg_replace. Please check PHP manual for more details
I'm trying to convert csv imported numbers from (5.25) to -5.25 to be imported into a DB.
$CSV[] = 'abcd';
$CSV[] = '(5.25)';
foreach($CSV as $Record){
if(preg_match_all("/[()]/", $Record, $output_array)){
$Record = '-' . preg_replace("/[()]/", '', $Record);
}
}
However, because i need to run this conversion on each record in the csv, and we don't know if the data in the column will be a number or some text, I need to only convert the string if both characters are present and wrapping the number.
Is this the proper way to use preg_match and preg_replace? It seems to be returning true to everything and essentially adding a dash "-" to every csv column.
you want something like this:
$CSV[] = 'abcd';
$CSV[] = '(5.25)';
$Record = array();
foreach($CSV as $value){
$Record[] = preg_replace("/\(([^a-zA-Z]+?)\)/", '-$1', $value);
}
var_dump($Record);
(\s|^)⇢(\s|$)|(\s|^)⇠(\s|$)
Searches if character ⇢ or ⇠ exists
I have a php value coming back from my database as a string, like
"this, that, another, another"
And I'm trying to wrap a separate link around each of those strings, but I can't seem to get it to work. I've tried a for loop, but since it's just a string of information and not an array of information that doesn't really work. Is there a way to wrap a unique link around each value in my string?
The easiest way that I see to do this would be using PHP's explode() function. You'll find that it will become very useful as you start to use PHP more and more, so do check out its documentation page. It allows you to split a string up into an array given a certain separator. In your case, this would be ,. So to split the string:
$string = 'this, that, another, another 2';
$parts = explode(', ', $string);
Then use a foreach (again, check the documentation) to iterate through each of the parts and make them into a link:
foreach($parts as $part) {
echo '' . $part . "\n";
}
However, you can do this with a for loop. Strings can be accessed like arrays, so you can implement a parser pattern to parse the string, extract the parts, and create the links.
// Initialize some vars that we'll need
$str = "this, that, another, another";
$output = ""; // final output
$buffer = ""; // buffer to hold current part
// Iterate over each character
for($i = 0; $i < strlen($str); $i++) {
// If the character is our separator
if($str[$i] === ',') {
// We've reached the end of this part, so add it to our output
$output .= '' . trim($buffer) . "\n";
// clear it so we can start storing the next part
$buffer = "";
// and skip to the next character
continue;
}
// Otherwise, add the character to the buffer for the current part
$buffer .= $str[$i];
}
echo $output;
(Codepad Demo)
A better way is to do it like this
$string = "this, that, another, another";
$ex_string = explode(",",$string);
foreach($ex_string AS $item)
{
echo "<a href='#'>".$item."</a><br />";
}
First explode the string to get the individual words in an array. Then add the hyperlinks to the words and finally implode them.
$string = "this, that, another, another";
$words = explode(",", $string);
$words[0] = $words[0]
$words[1] = $words[1]
..
$string = implode(",", $words);
You can also use the for loop to assign hyperlinks that follow a pattern like this:
for ($i=0; $i<count($words); $i++) {
//assign URL for each word as its name or index
}
I need your help with a slight problem I have. How can I update a portion of group of text separated by comma. When the text is entered into the database, it's a single line of text with commas between each words, but when I want to echo it out I use the explode function to separate them into individual words and not a single line of text like I have it in the database.
So my question now is, how can I make an update/Delete to a single word in the database. Remeber, I have it as a single line of text in the database, and I'm not interested in updating the whole line of text...just a single word in the text..
Thanks.
$text = "name,fname,lname,class,age" ;
$newtext = explode(",", $text) ;
Could use the replace() function in the sql update query.
Update table SET text=REPLACE(text,'age','newstring')
Update or remove the word from your array, then implode the array and save the new value to the database field.
//Remove all instances of $value from $array
function array_remove($array, $value) {
return array_filter($array, function ($e) use ($value) {
return $e != $value;
});
}
// Add only unique values
function array_add($array, $value) {
if (!in_array($value, $array))
$array[] = $value;
return $array;
}
$text = "name,fname,lname,class,age" ;
$newtext = explode(",", $text) ;
$newtext = array_remove($newtext, 'lname'); // Remove lname
$newtext = array_add($newtext, 'mail'); // Add mail
$newtext = array_add($newtext, 'class'); // Won't add it again
$newtext = implode(',', $newtext); // name,fname,class,age,mail
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$fdat = str_replace($filtr,"",$data);
$clean = implode(",",$fdat);
echo $clean;
this gives out put ,,searchengine,seo,search
How can I get rid of first two blank commas?
Better get the difference of your splitted arrays $exp minus $filtr:
$clean = implode(',', array_diff($exp, $filtr));
This will also avoid the chance that you will only remove a substring of another word like when removing car from bike,car,carpet should result in bike,carpet and not in bike,pet.
And if you want to allow whitespace before and after each word, consider using trim and preg_split:
$exp = preg_split('/\s*,\s*/', trim($data));
trim will remove any preceding and trailing whitespace and the pattern for preg_split allows whitespace surrounding the comma too.
I'm getting an error when trying this code you did. You can use the following to remove google & bing (that are in an array) from a comma separated string:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$diff = array_diff($exp, $filtr);
$clean = implode(",",$diff);
echo $clean;
Your piece of code could also look like this:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
foreach ($exp as $key => $item) {
if (in_array($key, $filtr)) unset($exp[$key]);
}
$clean = implode(",",$exp);
echo $clean;
Its useful when there is few items in $data. For big arrays it would need optimizing.
You would be better if checking the value within a loop like so:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
foreach($exp as $k => $v)
{
if(in_array($v,$filtr))
{
unset($ext[$k]);
}
}
$clean = implode(",",$ext);
echo $clean;