I have made this line of code to make the words, that is searced for, enhanced.
$tekst = preg_replace("/($searchstr)/i", '<span style="color: 8fb842; font-weight: bold;">$1</span>', $tekst);
But my problem is, that when I make $searchstr = '?'; it is setting between every letter in the $tekst string.
The whole script is:
/////////////////////////////////
// Set variables and arrays
/////////////////////////////////
$arr_sim = array();
if( !empty($_GET['search']) )
{
$text=strtolower($_GET['search']);
$code_entities_replace = array(' ','--','"','!','#','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','~','`','=', 'Æ', 'æ', 'æ', 'ø', 'Ø', 'ø', 'å', 'å', 'Å');
$code_entities_match = array('-','--','','_quot_','_s_','_s-a_','_sq_','procent','_tria_','_and_','_star_','_par-st_','_par-end_','_us_','_plus_','_tub-st_','_tub-end_','_line_','_col_','_anf_','_lt_','_st_','_qm_','_sqpar-s_','_sqpar-e_','_backsla2_', '_semcol_','_1anf_','_comma_','_punc_','_slash_','_nearequ_', '_msql-anf_', '_equal_', 'ae', 'ae', 'ae', 'oe', 'oe', 'oe', 'aa', 'aa', 'aa');
$text = str_replace($code_entities_match, $code_entities_replace, $text);
$searchstr = $text;
$search_str = $showpages->escape_str($text);
$showpages->_table = 'pages';
$showpages->_where = " tekst LIKE '%". $search_str . "%' AND language_id = '" . $_SESSION['lang_id']. "'";
$showpages->_orderby = 'id';
$showpages->_order = 'desc';
$f = $showpages->search();
while ( $row = mysql_fetch_array($f) )
{
$arr_text = explode(" ",$row['tekst']);
$percent = 0;
$words = count($arr_text);
foreach( $arr_text as $k => $v )
{
similar_text($search_str, $v, $p);
$percent += $p;
}
$percent = $percent / $words;
$arr_sim[] = array('percent' => $percent, 'id' => $row['id']);
}
}
/////////////////////////////////
// Set some variables
/////////////////////////////////
$arr_len = count($arr_sim);
if( !empty($_GET['offset']) )
$offset = $showpages->escape_str($_GET['offset']);
else
$offset = 0;
if( $arr_len >= 15 )
{
$limit = 15;
} else {
$limit = $arr_len;
}
$start = $offset+$limit;
rsort($arr_sim); // Sort the array to make the script show in the right order.
/////////////////////////////////
///////////////////
// Show content
////////////////////
if( $arr_len > 0 )
// check if the search is performed and any hits were found.
{
for( $i = $offset; $i < $start; $i++)
{
// $arr_sim[$i]['id']
$showpages->_table = 'pages';
$showpages->_id = $arr_sim[$i]['id'];
$showpages->_orderby = 'id';
$showpages->_order = 'desc';
$z = $showpages->search();
$r = $showpages->fetch_array( $z );
$tekst = strip_tags($r['tekst'], "<p><a>");
$str_pos = strpos($tekst, $searchstr);
if( $str_pos > 50 ){
$start_str = '...';
if(strlen($tekst) > 200)
{
$end_str = '...';
}
$tekst = substr($tekst, $str_pos-50, 200);
} else {
$start_str = '';
if(strlen($tekst) > 200)
{
$end_str = '...';
}
$tekst = substr($tekst, 0, 200);
}
$tekst = preg_replace("/($searchstr)/i", '<span style="color: 8fb842; font-weight: bold;">$1</span>', $tekst);
$dataa .= '<style type="text/css">.search-fr { margin-bottom: 15px; } .search-fr a {padding: 0; margin: 0 0 5px 0; font-weight: bold; font-size: 14px;} .search-fr p { padding: 0; margin: 0;}</style>';
$dataa .= '<div class="search-fr">';
$dataa .= '' . $r['emne'] . ' - Matcher din søgning <b>'. round($arr_sim[$i]['percent']).'%</b><br />';
$dataa .= $start_str.$tekst.$end_str;
$dataa .= '</div>';
}
} else {
$dataa .= 'Der er ikke fundet nogle sider, der matcher din søgning. Prøv igen.';
}
You can run the preg_quote() function on $searchstr which will escape any metacharacters before the string is used as your pattern.
For example:
$tekst = preg_replace('/'.preg_quote($searchstr, '/').'/i', '<span style="color: 8fb842; font-weight: bold;">$1</span>', $tekst);
Related
I want to print a string with this colors:
yellow, when a char is an odd number;
blue, when a char is an even number;
red, when a char is a vowel;
green, a the char is a consonant;
For example: $string = "hi12";
h = green
i = red
1 = yellow
2 = blue
I've tried with this but it does not seem to work:
$string = "hi12"; <br>
$strCol = ""; <br>
$char = ""; <br>
$color = ""; <br>
for($i = 0; $i < strlen($string); $i++){
$char = $string[$i];
if(is_numeric($char)){
if(($char % 2) == 1){
$color = "<p style='color:yellow;'>" + $char + "</p>";
$strCol .= $color;
}
else if(($char % 2) == 0){
$color = "<p style='color:blue;'>" + $char + "</p>";
$strCol .= $color;
}
}
else{
if(preg_match('/^[aeiou]/i', $char)){
$color = "<p style='color:red;'>" + $char + "</p>";
$strCol .= $color;
}
else{
$color = "<p style='color:green;'>" + $char + "</p>";
$strCol .= $color;
}
}
}
echo $strCol;
$isGreen = false;
$isRed = false;
$isYellow = false;
$isBlue = false;
$string = 'some text with space';
$letterCount = strlen($string) - substr_count($string, ' ');
if (0 == $letterCount % 4) {
$isBlue = true;
} elseif (1 == $letterCount % 4) {
$isGreen = true;
} elseif (2 == $letterCount % 4) {
$isRed = true;
} else {
$isYellow = true;
}
for ($i = strlen($string) - 1; $i >= 0; $i--) {
$letter = substr($string, $i, 1);
if (' ' == $letter) {
continue;
}
if ($isGreen) {
$colour = 'green';
$isGreen = !$isGreen;
$isBlue = !$isBlue;
} elseif ($isRed) {
$colour = 'red';
$isGreen = !$isGreen;
$isRed = !$isRed;
} elseif ($isYellow) {
$colour = 'yellow';
$isRed = !$isRed;
$isYellow = !$isYellow;
} else {
$colour = 'blue';
$isBlue = !$isBlue;
$isYellow = !$isYellow;
}
$string = substr_replace($string, sprintf('<span style="color:%s">%s</span>', $colour, $letter) , $i, 1);
}
echo $string;
I have a php script running on a regular basis that processes the top 100 rows of a CSV file. When it is done I want it to delete the processed rows from the CSV file.
I have tried the below code, but it does not delete anything. I am not sure the best way to state the condition in PHP and am not sure what to put for the $id. I set the number of rows at 5 for testing purposes. Likely have somy syntax wrong.
Any suggestions? Tips?
function delete_line($id)
{
if($id)
{
$file_handle = fopen("file.csv", "w+");
$myCsv = array();
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
}
$in = fopen( 'file.csv', 'r');
$out = fopen( 'file.csv', 'w');
// Check whether they opened
while( $row = fgetcsv( $in, $cnt)){
fputcsv( $out, $row);
}
fclose( $in); fclose( $out);
Whole script is here...
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
//print_r($_FILES);
//if($_FILES['file']['tmp_name']) {
//$upload = ABSPATH . 'file.csv';
//move_uploaded_file($_FILES['file']['tmp_name'], $upload);
//}
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 5;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' => $google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' => $google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' => $google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' => $geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
function delete_line($id)
{
if($id)
{
$file_handle = fopen("file.csv", "w+");
$myCsv = array();
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
}
$in = fopen( 'file.csv', 'r');
$out = fopen( 'file.csv', 'w');
// Check whether they opened
while( $row = fgetcsv( $in, $cnt)){
fputcsv( $out, $row);
}
fclose( $in); fclose( $out);
?>
Update
I tried one of the answer codes and got a server error. Code below, thoughts?
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
//print_r($_FILES);
//if($_FILES['file']['tmp_name']) {
//$upload = ABSPATH . 'file.csv';
//move_uploaded_file($_FILES['file']['tmp_name'], $upload);
//}
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 5;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' => $google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' => $google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' => $google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' => $geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
function csv_delete_rows($filename='file.csv', $startrow=1, $endrow=5, $inner=false) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
?>
<html>
<body>
<form enctype="multipart/form-data" method="post">
CSV: <input name="file" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
Here is php code for that:
$input = explode("\n", file_get_contents("file.csv"));
foreach ($input as $line) {
// process all lines.
}
// This function removes first 100 elements.
// More info:
// http://php.net/manual/en/function.array-slice.php
$output = array_slice($input, 100);
file_put_contents("out.csv", implode("\n", $output));
Note, if csv file contains header you have to remove first element from array $input.
I used this script in the passed written by Joby Joseph:
function csv_delete_rows($filename=NULL, $startrow=0, $endrow=0, $inner=true) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
The function accepts 4 parameters:
filename (string): Path to csv file. Eg: myfile.csv
startRow (int): First row in delete area
endRow (int): Last row in delete area
inner (boolean): decide whether rows deleted are from inner area or outer area
Now Let us consider various cases. I have a csv file with me named ‘test.csv’. Here is the screenshot of the same.
Example 1:
$status = csv_delete_rows('test.csv', 3, 5, true);
will delete the red part of:
Example 2:
$status = csv_delete_rows('test.csv', 3, 5, false);
will delete the red part of:
Example 3:
Like in your situation, if you want to delete the first 100 rows, use this:
$status = csv_delete_rows('test.csv', 0, 100);
I have list of brands and want to provide a search function with highlighting. For example, there are the following brands
Apple
Cewe Color
L'Oréal
Microsoft
McDonald's
Tom Tailor
The user then types lor in search form. I'm using the following snippet for searching
class search {
private function simplify($str) {
return str_replace(array('&',' ',',','.','?','|','\'','"'), '', iconv('UTF-8', 'ASCII//TRANSLIT', $str));
}
public function do_search($search) {
$search = self::simplify($search);
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr(self::simplify($brand['name']), $search) !== false) $found[]= $brand;
}
return $found;
}
}
That gives me:
Cewe Color
L'Oréal
Tom Tailor
How would be a highlighting possible? Like:
Cewe Co<b>lor</b>
L'<b>Oré</b>al
Tom Tai<b>lor</b>
Btw: I know, that most things can be done with str_replace(), but that fit my needs not in all cases
$highlighted = str_replace($search, "<b>$search</b>", $brand);
would be the simplest method.
:)
Works with FedEx also ;)
$_brands = array
(
"Apple",
"Cewe Color",
"L'Oréal",
"Microsoft",
"McDonald's",
"Tom Tailor"
);
$q = 'lor';
$search = clean($q);
foreach($_brands as $key => $brand){
$brand = clean($brand);
$x = stripos($brand, $search);
if($x !== false){
$regexp = NULL;
$l = strlen($q);
for($i = 0; $i < $l; $i++){
$regexp .= mb_strtoupper($q[$i]).'.?';
}
$regexp = substr($regexp, 0, strlen($regexp) - 2);
$new = $_brands[$key];
$new = preg_replace('#('.$regexp.')#ui', '<b>$0</b>', $new);
echo $new."<br />";
}
}
function clean($string){
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
$string = preg_replace('#[^\w]#ui', '', $string);
return $string;
}
self::$_brands contains result from database (containing columns name, name_lower, name_translit, name_simplified)
class search {
private function translit($str) {
return iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', str_replace(array('ä', 'ü', 'ö', 'ß'), array('a', 'u', 'o', 's'), mb_strtolower($str)));
}
private function simplify($str) {
return preg_replace('/([^a-z0-9])/ui', '', self::translit($str));
}
public function do_search($simplified) {
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr($brand['name_simplified'], $simplified) !== false) $found[]= $brand;
}
return $found;
}
private function actionDefault() {
$search = $_POST['search_fld'];
$simplified = self::simplify($search);
$result = self::do_search($simplified);
$brands = array();
foreach ($result as $brand) {
$hl_start = mb_strpos($brand['name_simplified'], $simplified);
$hl_len = mb_strlen($simplified);
$brand_len = mb_strlen($brand['name']);
$tmp = '';
$cnt_extra = 0;
$start_tag = false;
$end_tag = false;
for ($i = 0; $i < $brand_len; $i++) {
if (($i - $cnt_extra) < mb_strlen($brand['name_simplified']) && mb_substr($brand['name_translit'], $i, 1) != mb_substr($brand['name_simplified'], $i - $cnt_extra, 1)) $cnt_extra++;
if (($i - $cnt_extra) == $hl_start && !$start_tag) {
$tmp .= '<b>';
$start_tag = true;
}
$tmp .= mb_substr($brand['name'], $i, 1);
if (($i - $cnt_extra + 1) == ($hl_start + $hl_len) && !$end_tag) {
$tmp .= '</b>';
$end_tag = true;
}
}
if ($start_tag && !$end_tag) $tmp .= '</b>';
$brands[] = "" . $tmp . "";
}
echo implode(' | ', $brands);
}
}
Given a font CSS string such as this:
font:italic bold 12px/30px Georgia, serif;
or
font:12px verdana;
I want to convert it to its long hand format i.e:
font-style: italic; font-weight: bold;
Here is my miserable attempt: http://pastebin.com/e3KdMvGT
But of course it doesn't work for the second example since its expecting things to be in order, how can I improve it?
Here is a function which should do the work. The problem lies in the font-style, font-variant and font-weight properties and the value "normal" as you can read in the css specs ([[ <'font-style'> || <'font-variant'> || <'font-weight'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ] | caption | icon | menu | message-box | small-caption | status-bar | inherit).
$testStrings = array('12px/14px sans-serif',
'80% sans-serif',
'x-large/110% "New Century Schoolbook", serif',
'x-large/110% "New Century Schoolbook"',
'bold italic large Palatino, serif ',
'normal small-caps 120%/120% fantasy',
'italic bold 12px/30px Georgia, serif',
'12px verdana');
foreach($testStrings as $font){
echo "Test ($font)\n<pre>
";
$details = extractFull($font);
print_r($details);
echo "
</pre>";
}
function extractFull($fontString){
// Split $fontString. The only area where quotes should be found is around font-families. Which are at the end.
$parts = preg_split('`("|\')`', $fontString, 2, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$chunks = preg_split('` `', $parts[0], NULL, PREG_SPLIT_NO_EMPTY);
if(isset($parts[1])){
$chunks[] = $parts[1] . $parts[2];
}
$details = array();
$next = -1;
// Manage font-style / font-variant / font-weight properties
$possibilities = array();
$fontStyle = array('italic', 'oblique');
$fontVariant = array('small-caps');
$fontWeight = array('bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900');
// First pass on chunks 0 to 2 to see what each can be
for($i = 0; $i < 3; $i++){
$possibilities[$i] = array();
if(!isset($chunks[$i])){
if($next == -1){
$next = $i;
}
continue;
}
if(in_array($chunks[$i], $fontStyle)){
$possibilities[$i] = 'font-style';
}
else if(in_array($chunks[$i], $fontVariant)){
$possibilities[$i] = 'font-variant';
}
else if(in_array($chunks[$i], $fontWeight)){
$possibilities[$i] = 'font-weight';
}
else if($chunks[$i] == 'normal'){
$possibilities['normal'] = 1;
}
else if($next == -1){
// Used to know where other properties will start at
$next = $i;
}
}
// Second pass to determine what real properties are defined
for($i = 0; $i < 3; $i++){
if(!empty($possibilities[$i])){
$details[$possibilities[$i]] = $chunks[$i];
}
}
// Third pass to set the properties which have to be set as "normal"
if(!empty($possibilities['normal'])){
$properties = array('font-style', 'font-variant', 'font-weight');
foreach($properties as $property){
if(!isset($details[$property])){
$details[$property] = 'normal';
}
}
}
if(!isset($chunks[$next])){
return $details;
}
// Extract font-size and line height
if(strpos($chunks[$next], '/')){
$size = explode('/', $chunks[$next]);
$details['font-size'] = $size[0];
$details['line-height'] = $size[1];
$details['font-family'] = $chunks[$next+1];
}
else if(preg_match('`^-?[0-9]+`', $chunks[$next]) ||
in_array($chunks[$next], array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'))){
$details['font-size'] = $chunks[$next];
$details['font-family'] = $chunks[$next+1];
}
else{
$details['font-family'] = $chunks[$next];
}
return $details;
}
here my attempt
function rewriteFont($short) {
$short = str_replace("font:","",$short);
$values = explode(" ", $short);
$length = count($values);
$familyLength = 0;
for($i = 0; $i < $length; $i++) {
$currentValue = $values[$i];
if($currentValue == 'italic' || $currentValue == 'oblique' ) {
echo "font-style:{$currentValue};";
}
else if($currentValue == 'small-caps') {
echo "font-variant:{$currentValue};";
}
else if ($currentValue == 'bold' || $currentValue == 'bolder' || $currentValue == 'lighter' || is_numeric($currentValue) ) {
echo "font-weight:{$currentValue};";
}
else if (strpos($currentValue, "px") || strpos($currentValue, "em") || strpos($currentValue, "ex")|| strpos($currentValue, "pt")
|| strpos($currentValue, "%") || $currentValue == "xx-small" || $currentValue == "x-small" || $currentValue == "small"
|| $currentValue == "medium" || $currentValue == "large" || $currentValue == "x-large" || $currentValue == "xx-large") {
$sizeLineHeight = explode("/", $currentValue);
echo "font-size:{$sizeLineHeight[0]};";
if(isset($sizeLineHeight[1])) {
echo "line-height:{$sizeLineHeight[1]};";
}
}
else {
if($familyLength == 0) {
echo "font-family:{$currentValue} ";
}
else {
echo $currentValue;
}
$familyLength++;
}
}
}
Following the specs, I'd do the following code. It works with all examples from the specs. You can see it here : http://codepad.viper-7.com/ABhc22
function font($s){
$fontStyle = array('normal', 'italic', 'oblique', 'inherit');
$fontVariant = array('normal', 'small-caps','inherit');
$fontSize = array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large');
$fontWeight = array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'inherit');
$s = str_replace('font: ', '', $s);
$array = explode(' ', $s);
$count = count($array);
$sizeFound = false;
$final = array();
$final['font-style'] = 'normal';
$final['font-variant'] = 'normal';
$final['font-weight'] = 'normal';
for($i = 0; $i < $count; $i++){
$cur = $array[$i];
if($sizeFound){
$final['font-family'] = isset($final['font-family']) ? $final['font-family'].$cur : $cur;
}else if(strripos($cur,'%') !== false || strripos($cur,'px') !== false || in_array($cur, $fontSize)){
$sizeFound = true;
$size = explode('/', $cur);
if(count($size) > 1){
$final['font-size'] = $size[0];
$final['line-height'] = $size[1];
}else
$final['font-size'] = $size[0];
}else{
if(in_array($cur, $fontStyle))
$final['font-style'] = $cur;
if(in_array($cur, $fontVariant))
$final['font-variant'] = $cur;
if(in_array($cur, $fontWeight))
$final['font-weight'] = $cur;
}
}
$ret = '';
foreach($final as $prop => $val)
$ret .= $prop.': '.$val.';';
return $ret;
}
I guess it can be optimised. :)
You could look at CSSTidy, whose code is open-source and try to reverse engineer it.
I'm using this function:
function getmyimages($qid){
$imgdir = 'modules/Projects/uploaded_project_images/'. $qid .''; // the directory, where your images are stored
$allowed_types = array('png','jpg','jpeg','gif'); // list of filetypes you want to show
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
{
$a_img[] = $imgfile;
sort($a_img);
reset ($a_img);
}
}
$totimg = count($a_img); // total image number
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
}
And I call this function between a while row as:
$sql_select = $db->sql_query('SELECT * from '.$prefix.'_projects WHERE topic=\''.$cid.'\'');
OpenTable();
while ($row2 = $db->sql_fetchrow($sql_select)){
$qid = $row2['qid'];
$project_query = $db->sql_query('SELECT p.uid, p.uname, p.subject, p.story, p.storyext, p.date, p.topic, p.pdate, p.materials, p.bidoptions, p.projectduration, pd.id_duration, pm.material_id, pbo.bidid, pc.cid FROM ' . $prefix . '_projects p, ' . $prefix . '_projects_duration pd, ' . $prefix . '_project_materials pm, ' . $prefix . '_project_bid_options pbo, ' . $prefix . '_project_categories pc WHERE p.topic=\''.$cid.'\' and p.qid=\''.$qid.'\' and p.bidoptions=pbo.bidid and p.materials=pm.material_id and p.projectduration=pd.id_duration');
while ($project_row = $db->sql_fetchrow($project_query)) {
//$qid = $project_row['qid'];
$uid = $project_row['uid'];
$uname = $project_row['uname'];
$subject = $project_row['subject'];
$story = $project_row['story'];
$storyext = $project_row['storyext'];
$date = $project_row['date'];
$topic = $project_row['topic'];
$pdate = $project_row['pdate'];
$materials = $project_row['materials'];
$bidoptions = $project_row['bidoptions'];
$projectduration = $project_row['projectduration'];
//Get the topic name
$topic_query = $db->sql_query('SELECT cid,title from '.$prefix.'_project_categories WHERE cid =\''.$cid.'\'');
while ($topic_row = $db->sql_fetchrow($topic_query)) {
$topic_id = $topic_row['cid'];
$topic_title = $topic_row['title'];
}
//Get the material text
$material_query = $db->sql_query('SELECT material_id,material_name from '.$prefix.'_project_materials WHERE material_id =\''.$materials.'\'');
while ($material_row = $db->sql_fetchrow($material_query)) {
$material_id = $material_row['material_id'];
$material_name = $material_row['material_name'];
}
//Get the bid methode
$bid_query = $db->sql_query('SELECT bidid,bidname from '.$prefix.'_project_bid_options WHERE bidid =\''.$bidoptions.'\'');
while ($bid_row = $db->sql_fetchrow($bid_query)) {
$bidid = $bid_row['bidid'];
$bidname = $bid_row['bidname'];
}
//Get the project duration
$duration_query = $db->sql_query('SELECT id_duration,duration_value,duration_alias from '.$prefix.'_projects_duration WHERE id_duration =\''.$projectduration.'\'');
while ($duration_row = $db->sql_fetchrow($duration_query)) {
$id_duration = $duration_row['id_duration'];
$duration_value = $duration_row['duration_value'];
$duration_alias = $duration_row['duration_alias'];
}
}
echo '<br/><b>id</b>--->' .$qid. '<br/><b>uid</b>--->' .$uid. '<br/><b>username</b>--->' .$uname. '<br/><b>subject</b>--->'.$subject. '<br/><b>story1</b>--->'.$story. '<br/><b>story2</b>--->'.$storyext. '<br/><b>postdate</b>--->'.$date. '<br/><b>categorie</b>--->'.$topic_title . '<br/><b>project start</b>--->'.$pdate. '<br/><b>materials</b>--->'.$material_name. '<br/><b>bid methode</b>--->'.$bidname. '<br/><b>project duration</b>--->'.$duration_alias.'<br /><br /><br/><b>image url</b>--->'.getmyimages($qid).'<br /><br />';
}
CloseTable();
The result outputs only the "last" file from the directories.
If I do an echo instead of a return $mytest;, it reads the whole directory but ruins the output.
You are always overwriting $mytest in your loop:
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
So after the loop, $mytest contains the last value that was generated in the loop. You might want to return an array instead:
$mytest = array();
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// do whatever
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
$mytest[] = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'. $a_img[$x]. '';
}
return $mytest;
But of course you also have to change your other function in order to deal with the returned array.