PHP - Renaming/replacing Names
Hi Guys,
I use this function to generate seo friendly names for my products once pulled from the database: function generate_seo_friendly_links($pNM, $pID) { $replacedNM = str_replace(" ", "-", $pNM); $replacedNM = rtrim($replacedNM); $brandNewSEOFriendlyURL = "<a href='$replacedNM-$pID.html'>$pNM</a>"; return $brandNewSEOFriendlyURL; } This works great, the only thing is say a product is stored in the database like: product name it would then be converted to: product-name.html if for example theres 2 spaces: product name it would then be converted to: product--name.html with the 2 "--" so for every space it finds we replace with a "-" etc is there a way i could ignore more than 1 space and always have it like product-name-here.html so the names are more uniformed, i can't think of a way to do it. any help would be appreciated thanks guys Graham Similar TutorialsMy Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsaneMy question would be a little out of topic... what i am doing is trying to create a music album website for my customer.. nd have to create a form to upload the .mp3 files... the file my customer have are like complete albums.. each album named as track01.mp3 , track02.mp3.. i rename them as getting a value from the text box where the user enter the correct name and this track01 gets renamed.. by default the .mp3 files have the correct song name in its <title> tag.. like everysong have there properties.. and title is one them.. the title of the song is present in title tag of the song property.. is there a way i can get that title be assigned as the name of the song and finish of this manual way of entry of the name of the song by the user? i hope u understand what i am saying.. i want what ever is in the title track to automatically be assigned to the name of the song... please help me if this is possible? Hi all I am writing a piece of code that takes the filename from a form and renames it so that the file overwrites the original in the directory. HEre's my code: if(!empty($_FILES['i1']['name'])) { copy($_FILES['i1']['tmp_name'], "/home/cqdesign/public_html/clientarea/argentequus/mobile/images/slideshow/".$_FILES['i1']['name']) or die("Error uploading image 1."); } This takes the file from the form where the name of the file is i1. I need it to then rename the file to i1.jpg. There are 9 different files with the same format. Many thanks for your help. Pete Hello, I made a site where to upload images. The images are saved to a directory (folder). After someoe uploads an image, he gets the link. For example, if someone has an image called "xxx.jpg", he gets the url like this: www.example.com/upload/xxx.jpg. What I want is, when someone uploads an images, the name of the image change to random numbers. I know the PHP function rand() and rename () function, but the only problem is, it is renaming the file without considering the file extension. Here is a sample of my codes: Code: [Select] $image = htmlentities($_FILES['file']['name']); $number = rand(1,1000); $newname = rename ($image, $number); echo $newname So, can someone tell me, how to rename images but taking into consideration of the file extension? If the image is xxx.jpg, I want it like 123.jpg not 123. I am reading hundreds of CSVs to import into a DB. Some of the column names contain the same data but have different names across all the files. For example, one file will say Phone where the other says EveningPhone...both contain the same data, different names. I am trying to rename everything to EveningPhone because I had most of the code done when i realized there were different header names in different files. Too lazy to replace all i guess.. I am creating an assoc array to match the data then off to the db it goes.. The problem is I cannot get the keys to rename to one convention. Here is the function where it happens: Code: [Select] public function readCSV($file) { /** * @todo: LOAD THE FILE INTO A MULTIDIMENSIONAL ASSOCIATIVE ARRAY TO DETERMINE THE FILEDS */ // Read the first line to get the headers $headers = fgetcsv($file); if (!array_key_exists('EveningPhone', $headers)) { if (array_key_exists('Phone', $headers)) { $headers['EveningPhone'] = $headers['Phone']; unset($headers['Phone']); } else { die("other"); } } format::neat_r($headers); // basically print_r but adds a new line to read it easier... die(); At the end, I still get EveningPhone not defined errors from a file that uses Phone as the phone number.. Anybody have any ideas? Can someone help me in renaming an uploaded file with parameters from the input fields named firstname and lastname? I would like to name each uploaded file with the firstname and lastname along with a random number and then the file extension, but I am having trouble getting it right. Here is what I have so far: Code: [Select] <?php $firstname = ""; $lastname = ""; $address = ""; $city = ""; $state = ""; $zip = ""; $phone = ""; $position = ""; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>KulaE_WDP4451_U2IP</title> </head> <body> <form action="process_U2IP.php" method="post" enctype="multipart/form-data"> <h3>Please fill out the form below and upload your resume to apply for a position within our company:</h3> <table> <tr> <td><label for="firstname"><b>First Name*</b></label></td> <td><input name="firstname" type="text" size="20" id="firstname" value="<?php echo $lastname; ?>" /></td> </tr> <tr> <td><label for="lastname"><b>Last Name*</b></label></td> <td><input name="lastname" type="text" size="20" id="lastname" value="<?php echo $lastname; ?>" /></td> </tr> <tr> <td><label for="address"><b>Address*</b></label></td> <td><input name="address" type="text" size="20" id="address" value="<?php echo $address; ?>" /></td> </tr> <tr> <td><label for="city"><b>City*</b></label></td> <td><input name="city" type="text" size="20" id="city" value="<?php echo $city; ?>" /></td> </tr> <tr> <td><label for="state"><b>State*</b></label></td> <td><input name="state" type="text" size="20" id="state" value="<?php echo $state; ?>" /></td> </tr> <tr> <td><label for="zip"><b>Zip*</b></label></td> <td><input name="zip" type="text" size="20" id="zip" value="<?php echo $zip; ?>" /></td> </tr> <tr> <td><label for="phone"><b>Phone*</b></label></td> <td><input name="phone" type="text" size="20" id="phone" value="<?php echo $phone; ?>" /></td> </tr> <tr> <td><label for="position"><b>Position*</b></label></td> <td><input name="position" type="text" size="20" id="position" value="<?php echo $position; ?>" /></td> </tr> <tr> <td><b>Upload Resume*</b></td> <td><input type="file" name="file" id="file" /> </td> </tr> <tr> <td colspan="2"><p><i>Your information will not be sold or shared with others.</i></p></td> </tr> <tr> <td colspan="2"><p style="color: red;">* denotes required field</p></td> </tr> <tr> <td colspan="2" align="center"><input type="hidden" name="submitted" value="1" /> <input type="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></td> </tr> </table> </form> </body> </html> Code: [Select] <?php if (@$_POST['submitted']){ $firstname = (@$_POST['firstname']); $lastname = (@$_POST['lastname']); $address = (@$_POST['address']); $city = (@$_POST['city']); $state = (@$_POST['state']); $zip = (@$_POST['zip']); $phone = (@$_POST['phone']); $position = (@$_POST['position']); $file = (@$_POST['file']); if (get_magic_quotes_gpc()){ $firstname = stripslashes($firstname); $lastname = stripslashes($lastname); $address = stripslashes($address); $city = stripslashes($city); $state = stripslashes($state); $zip = stripslashes($zip); $phone = stripslashes($phone); $position = stripslashes($position); } $error_msg=array(); if ($firstname==""){ $error_msg[]="Please enter your first name"; } if(!preg_match("/^\b[a-zA-Z]+\b$/", $firstname)){ $error_msg[]="First Name can only contain letters"; } if ($lastname==""){ $error_msg[]="Please enter your last name"; } if(!preg_match("/^\b[a-zA-Z]+\b$/", $lastname)){ $error_msg[]="Last Name can only contain letters"; } if ($address==""){ $error_msg[]="Please enter your address"; } if(!preg_match('/^[a-z0-9 ]*$/i', $address)){ $error_msg[]="Address can only contain numbers, letters and spaces"; } if ($city==""){ $error_msg[]="Please enter your city"; } if (!preg_match("/^\b[a-zA-Z]+\b$/", $city)){ $error_msg[]="City can only contain letters"; } if ($state==""){ $error_msg[]="Please enter your state"; } if (strlen($state)<>2){ $error_msg[]="State can only contain 2 letters; use state abbreviation"; } if (!preg_match("/^\b[a-zA-Z]+\b$/", $state)){ $error_msg[]="State can only contain letters"; } if ($zip==""){ $error_msg[]="Please enter your zip code"; } if (strlen($zip)<>5){ $error_msg[]="Zip code can only contain 5 digits"; } if(!is_numeric($zip)){ $error_msg[]="Zip code must contain only numbers"; } if ($phone==""){ $error_msg[]="Please enter your phone number"; } if (strlen($phone)<>10){ $error_msg[]="Phone number can only contain 10 digits"; } if(!is_numeric($phone)){ $error_msg[]="Phone number must contain only numbers"; } if ($position==""){ $error_msg[]="Please enter your desired position"; } if(!preg_match('/^[a-z0-9 ]*$/i', $position)){ $error_msg[]="Position can only contain numbers, letters and spaces"; } if (file_exists("upload/" . $_FILES["file"]["name"])) { $error_msg[]= $_FILES["file"]["name"] . " already exists"; } if ((($_FILES["file"]["type"] != "document/msword") || ($_FILES["file"]["type"] != "document/pdf")) && ($_FILES["file"]["size"] > 20000)) { $error_msg[]= "Uploaded file can only be in MSWord or PDF format and can only be under 20KB in size"; } } if ($error_msg){ $display_errors = "<h3>There were errors in your submission.</h3> <p>Please review the following errors, press the Back button on your browser, and make corrections before re-submitting.</p> <ul style=color:red>\n"; foreach ($error_msg as $err){ $display_errors .= "<li>".$err."</li>\n"; } $display_errors .= "</ul>\n"; } if (!$error_msg){ echo " <h3>Thank you for applying! Applicants we are interested in interviewing will be contacted within 48 hours.</h3> <p>You have submitted the following information:</p> <table> <tr> <td><b>First Name:</b></td> <td>$firstname</td> </tr> <tr> <td><b>Last Name:</b></td> <td>$lastname</td> </tr> <tr> <td><b>Address:</b></td> <td>$address</td> </tr> <tr> <td><b>City:</b></td> <td>$city</td> </tr> <tr> <td><b>State:</b></td> <td>$state</td> </tr> <tr> <td><b>Zip Code:</b></td> <td>$zip</td> </tr> <tr> <td><b>Phone Number:</b></td> <td>$phone</td> </tr> <tr> <td><b>Position Desired:</b></td> <td>$position</td> </tr>"; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "<tr> <td><b>Uploaded File:</b></td> <td><a href=upload/" . $_FILES["file"]["name"] . ">" . $_FILES["file"]["name"] . "</a></td> </tr> </table>"; exit(); } echo $display_errors; ?> I found the following help online, but I can't get it right. Can anyone help? Code: [Select] <?php //This function separates the extension from the rest of the file name and returns it function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //This applies the function to our file $ext = findexts ($_FILES['uploaded']['name']) ; //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. $ran = rand () ; //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended. $ran2 = $ran."."; //This assigns the subdirectory you want to save into... make sure it exists! $target = "images/"; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; } ?> Hi Is there a way I can change my script to auto name the file when its being stored? Maybe by numbers lets say each time I upload a picture it should rename it to the number after the previous number.
like example"
Upload 1: 1.jpg
Upload 2: 2.jpg etc..
My current code I have is as follow
Form.html
<html> <body><br> <h1>My upload file form.</h1> <form enctype="multipart/form-data" action="process.php" method="post"> Enter File Name:<input type="text" name="name" value="Please enter file name:" /><br> Enter Description:<input type="text" name="desc" value="Description:" /><br> Select image:<input type="file" name="prodImg"><br> <input type="submit" value="Submit Page" /> </form> <?php include "menu3.php"; ?> </body> </html>And my processing script process.php <?php extract($_POST); $name; $desc; $fileType = $_FILES['prodImg']['type']; $fileSize = $_FILES['prodImg']['size']; if($fileSize/1024 > '150') { echo 'Filesize is not correct it should equal to 2 MB or less than 2 MB.'; exit(); } //FileSize Checking if($fileType != 'image/gif' && $fileType != 'image/jpg' && $fileType != 'image/jpeg' ) { echo 'Sorry this file type is not supported we accept only. Jpeg, Gif, PNG, or '; exit(); } //file type checking ends here. $upFile = 'files/galaxywars/'.date('Y_m_d_H_i_s').$_FILES['prodImg']['name']; if(is_uploaded_file($_FILES['prodImg']['tmp_name'])) { if(!move_uploaded_file($_FILES['prodImg']['tmp_name'], $upFile)) { echo 'Problem could not move file to destination. Please check again later. <a href="index.php">Please go back.</a>'; exit; } } else { echo 'Problem: Possible file upload attack. Filename: '; echo $_FILES['prodImg']['name']; exit; } $prodImg = $upFile; //File upload ends here. $upFile; echo "Thank you for sending your file"; ?> <?php include "menu3.php"; ?>Can anyone assist me with this problem please? I wrote this script to rename my many tv series I have on my pc, works by finding a string in the file name and replacing it
the script works fine until I want to replace the file name with something that is also in the path
file = band ep01.avi
path = j:\media\ TV shows\Band of Brothers\
so if I try to change "Band" to "Band of Brothers" the path changes as well
is there a way I can change the code so it dosent effect the path ??
<?php $path = 'J:\media\TV shows\Band of Brothers'; foreach(glob($path.'/*.*') as $filename){ echo $filename."</BR>"; } ?> <table align="center" width="200px" border="0" cellspacing="1" cellpadding="3"> <form name="form1" method="get" action="mov.php"> <tr> <td colspan="3"><strong> </strong></td> </tr> <tr> <td width="71">Replace</td> <td width="6">:</td> <td width="301"><input name="rep" type="text" id="rep"></td> </tr> <tr> <td>With</td> <td>:</td> <td><input name="with" type="text" id="with"></td> </tr> <tr> <tr> <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr></form> </table> <?php if (isset($_GET["rep"])) { $rep1=$_GET['rep']; } if (isset($_GET["with"])) { $with1=$_GET['with']; } foreach(glob($path.'/*.*') as $filename){ $strip = str_replace($rep1, $with1, $filename); echo $strip."</br>"; rename($filename,$strip); } ?> I'm using the following code in a WordPress functions file to rename a folder in the uploads folder according to the date, but this only works if the chmodd settings of both folders are 777. How can I change this code so I can use at least chmodd 755 to keep my website save. Code: [Select] date_default_timezone_set('Europe/Amsterdam'); // set timezone $foldername = ''; $source = 'uploads'; $allfolders = getDirectory($source); // get folders $folder = $source.'/'.$allfolders[0]; // get first folder $month = (int)date('n'); $day = (int)date('j'); $f = 50-$day; $s = 100-$month; $newfolder = $source.'/'.(string)$f.(string)$s; if($folder != '' && $folder != $newfolder){ rename($folder, $newfolder); $foldername = $newfolder."/"; }else if($folder == $newfolder){ $foldername = $newfolder."/"; } else{ $foldername = 'error'; } I have a folder containing files. I want to replace some characters in the file names (e.g. "_" with "-"), then make a list of new files (renamed ones). Thanks Please help. I am trying to replace parenthesises () in a string with <>. I tried preg_replace and str_replace, but was not success. Here is what I have for str_replace: $word = "(test)"; $word = str_replace('(', '<', $word); $word = str_replace(array('(', ')'), array('<','>'), $word); Hey guys, I have a quick question. Im going to be making a script that will output the name of a news article along with the poster's name beside it. There is only a certain amount of space where that stuff can go so I want to know how I can make it so that say after 20 characters, it ends and puts "..." beside it. Is this possible with php? How would I do it? Hello, Is str_replace the best way to go about this? In MYSQL, a html template is stored, such that: Quote <table width="{$width}">lots of other ........</table> This is extract from the database, and stored in a string. I would use eval(), but, any user can update this template, so I need to be able to set which variables will be replaced with what the variable is. Thanks! Hey all, i need a function or a way to replace each letter in a string to a star (*) Thanks How come this is not replacing correctly? $rp = strtr($rp,"[TIMES]","<span style='font-family: Times New Roman, Times, serif'>") hi freaks, still working on my email bot. im currently trying to escape <>-tags to be displayed- but not the browser wont exectute it (i.e. xls-tags) i want them as chars. so whin my $content is like <xsl:stylesheet> <xsl:template match="/"> <more xls...> it shows a stylesheet. i just want the chars. Here is what ive been trying so far: but its bad Code: [Select] <?php $string='<tag> > < asdasf'; $bomb=array( '<', '>', ); $defusal=array( '-', '!', ); $string= preg_replace($bomb,$defusal,$string); echo $string; ?> error: Warning: preg_replace() [function.preg-replace]: No ending matching delimiter '>' found in C:\xampp1\htdocs\code.php on line 13 donno any further now hi, i have an article with several paragraphs. However i would like the first paragraph to be converted into a header. string replacement will not work as it will replace all the p tags. i just want the 1st set of p tags to be replaced. can anyone help? thanks I'm having an issue with users uploading files with a Semi Colon in the file name. I am currently using a script that replaces characters within the file name, however, when I try to add a ";" as invalid characters to replace, it is like the semi-colon just stops the script, as the file does not upload (no errors are displayed). Here's the code I'm working with: $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\],~`-'; $file_name = preg_replace('/[^'.$valid_chars_regex.']|\'.+$/i', "", basename($_FILES[$upload_name]['name'])); if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) { HandleError("Invalid file name"); exit(0); } I tried placing the semi colon all over the place in the preg_replace function, but nothing seems to work. How can I do this? Hi first post here and very new to php. I built a form so that a data entry perosn can "build" new pages for our companies website. I pretty much have the basics of the form and the action page coded correctly, however my issue is that I need this final page where the form inputs are posted too to be an html document. I read some about the str_replace() function, but I'm not understanding how I could use that to replace the file extension of a page. Maybe I'm going about this all wrong. I also read that one can edit the htaccess folder to allow an html file to run php script. Not sure which way would be the best. One thing to mention though, is this application would be run locally to our back up files which is then scheduled to be uploaded to the remote server very night. Any help or suggestions would be greatly appreciated. |