PHP - Preg_replace - Stop From Replacing Matching Img Filename
I am wanting to replace certain words to make them bold and also linked. The code below is working however it is also replacing images that have the same filename therefore causing the image to be broken. How can I replace the word when it appears without replacing the filename when it appears.
<?php $find = array ("/$word/i","/A Duty of Care/i"); $replace = array ("<a href=/link.php?word=$word><b>$word</b></a>","<a href=/link.php>A Duty of Care</a>"); Echo preg_replace ($find, $replace, $definition); ?> Similar TutorialsHi I'm trying to match @USERNAME in a string and replace it with @<a href="message.php?member=USERNAME">USERNAME</a> I've tried a few different methods: Code: [Select] preg_replace ('/@(.*?)/', '<a href="message.php?member=$1">$1</a>', $str)and also * and \@ but i just can't seem to get it to work. any help would be appreciated! $customer_contact_id = preg_replace("`", "", $customer_contact_id); Am I doing something wrong? Every page that used the eregi_function, I changed to have it utilize the preg_function (because I saw a Youtube video telling me to do so). Now, every variable I perform the above on acts as if it doesn't exist. This has totally destroyed my system. What do I need to do here to fix things? I need to process a CSV file in database (MySql using LOAD DATA INFILE)), while the code is working fine but it works only with file that is already on my apache server (where php is installed). Is there any way (Java/Ajax or anything) that I can prompt user to select a file from any loaction they prefer including there desktop?? Thanks in advance!! I want to validate my PHP files to ensure that I didn't forget to import all the classes assigned to attributes. I will be using ReflectionClass to do so and need the FQCN's and not the filenames. Originally, I tried get_declared_classes(), however, ran into issues where a class was already declared. I came up with the following which appears to work, however, it was created based on trial and error and suspect there might be edge cases where it will not provide the desired results (and it is pretty damn ugly as well). How would you recommend doing so? A couple thoughts a Use composer to come up with the classes based on filename and use either vendor/Composer autoload_classmap.php or autoload_static.php. I don't really like this approach as it requires me to update composer to add any new files. Use composer but figure out how it generates the class map and use a similar approach. Appears that it is using phpstan or some other utility but I haven't really investigated. Use some third party script to generate the class maps. If so, please provide recommendations. Use some more modern approach other than PhpToken. If so, please provide recommendations. Use get_declared_classes() to get a base line and then require the PHP file to find the added class names and somehow deal with issues related to classes already being declared. Use tokens and my parseFile() method. If so, any recommendations on changing?PS. I originally wasn't 100% that attributes in traits and abstract classes would be propagated to the concrete class, but I should have known it to be true and this was confirmed by testing. At this time, I really just need the concrete classes, however, maybe in the future I will use the script to do some analysis on interfaces, traits, etc.
private function parseFile(string $filename):array { $getNext=null; $getNextNamespace=false; $skipNext=false; $isAbstract = false; $rs = ['namespace'=>null, 'class'=>[], 'trait'=>[], 'interface'=>[], 'abstract'=>[]]; foreach (\PhpToken::tokenize(file_get_contents($filename)) as $token) { if(!$token->isIgnorable()) { $name = $token->getTokenName(); switch($name){ case 'T_NAMESPACE': $getNextNamespace=true; break; case 'T_EXTENDS': case 'T_USE': case 'T_IMPLEMENTS': //case 'T_ATTRIBUTE': $skipNext = true; break; case 'T_ABSTRACT': $isAbstract = true; break; case 'T_CLASS': case 'T_TRAIT': case 'T_INTERFACE': if($skipNext) { $skipNext=false; } else { $getNext = strtolower(substr($name, 2)); } break; case 'T_NAME_QUALIFIED': case 'T_STRING': if($getNextNamespace) { if(array_filter($rs)) { throw new \Exception(sprintf('Namespace mus be defined first in %s', $filename)); } else { $rs['namespace'] = $token->text; } $getNextNamespace=false; } elseif($skipNext) { $skipNext=false; } elseif($getNext) { if(in_array($token->text, $rs[$getNext])) { throw new \Exception(sprintf('%s %s has already been found in %s', $rs[$getNext], $token->text, $filename)); } if($isAbstract) { $isAbstract=false; $getNext = 'abstract'; } $rs[$getNext][]=$token->text; $getNext=null; } break; default: $getNext=null; } } } $rs['filename'] = $filename; return $rs; }
Hi, I am struggling with a form in php. I am trying to add a form by using the include function. I want to include thsi form on all pages so it would be very useful if I can save the current page name somewhere so that I can use to validate the form. For example, this is the form I am trying to include. <?php if(!empty($errors)) { if(isset($errors['sendError'])) { echo '<p><strong class="error">There was a problem with our system please contact us directly.</strong></p>'; } else { echo '<p><strong class="error">Please check the form below for errors.</strong></p>'; } } ?> <form action="index.php" method="post" id="form1"> <p> <label><?php if(isset($errors['name'])) { echo '<span class="error">'; } ?>Name<font color="red">*</font>: <?php if(isset($errors['name'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['name']; ?>" name="name" size="60" align="right" style="background:#EEF5A4" /> <label><?php if(isset($errors['company'])) { echo '<span class="error">'; } ?>Company: <?php if(isset($errors['company'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['company']; ?>" name="company" size="60" align="right" /> <label><?php if(isset($errors['phone'])) { echo '<span class="error">'; } ?>Phone Number: <?php if(isset($errors['phone'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['phone']; ?>" name="phone" size="60" align="right" /> <label><?php if(isset($errors['email'])) { echo '<span class="error">'; } ?>Email<font color="red">*</font>: <?php if(isset($errors['email'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['email']; ?>" name="email" size="60" align="right" style="background:#EEF5A4" /> <label><?php if(isset($errors['enquiry'])) { echo '<span class="error">'; } ?>Enquiry: <?php if(isset($errors['enquiry'])) { echo '</span>'; } ?></label> <textarea id="search1" id="complete" textarea name="enquiry" rows=4 cols=40 value="<?php echo $form['enquiry']; ?>" name="enquiry" size="60" align="right"></textarea> </p> <p> <input type="submit" class="formbutton" value="Submit" /> <input type="reset" class="formbutton" value="Reset" /> </p> <p><font color="red">*</font> Denotes a required field</p> </form> Because I am going to use this form on all pages, I would like it to include whatever the filename is rather than index.php in the first line of the form so that when the user clicks submit, it will stay on the same page but validate the form based on the mandatory fields. I don't know if the question is clear. I would very much appreciate any help at all. Thank you very much. I am trying to get the actual filename so that I can attach it to an email. I tried echo $file; but its not giving me anything. Just a blank page. Here's the code that I' working with: $file = date('M-d-Y H:i A'). '.png'; $uri = substr($data,strpos($data,",")+1); file_put_contents('./Collection_Posts/'.$file, base64_decode($uri)); echo $file; exit;
Hello folks, I am new to the forum. I am having a problem on SBS 2011 creating a ZipArchive with PHP. Although I have specified the filename to create as "myzip.zip" the file created in the temp folder is "myzip.zip.a10860". If I try again immediately the file becomes "myzip.zip.b10860" and then "myzip.zip.c10860". Of course the numbers will change if I wait a few minutes. I have also tried creating the file first with fopen() then closing it and trying the ZipArchive::OVERWRITE. Still the same result I have tried many standard scripts from the net as well as my own very basic script and always the same result. PHP is set up through Fastcgi. Any thoughts would be appreciated. Michael Hi all, I am working on the PHP to fetch the data from the database. I would like to fetch the filename only following by: email1.png email2.png email3.png my_inbox.png
When I try this: $mailbox_sql = 'SELECT * FROM ' . $mailfolder . ' WHERE email_id = ? AND message_id = ?'; $mailbox = $link->prepare($mailbox_sql); $mailbox->execute([$id,$message_id]); // set the resulting array to associative $row = $mailbox->fetch(PDO::FETCH_ASSOC); if (is_array($row)) { $attached = $row['attached_files']; $attached_files_name = explode('attid: ', $attached); }
I am getting this: 0 filename: email1.png 1 filename: email2.png 2 filename: email3.png 3 filename: my_inbox.png
Here is what I have stored in the database: attid: 0 filename: email1.png attid: 1 filename: email2.png attid: 2 filename: email3.png attid: 3 filename: my_inbox.png
Here is what I want to achieve: email1.png email2.png email3.png my_inbox.png
Can you please show me example how I could get the filename when I am fetching the data from the database? Thanks in advance. Edited January 18, 2020 by mark107Is there a class out there that validates window filenames? Thank you. Hi everyone. I have a small problem. I have a database that shows student images, in the format of 1234.jpg but the file name extension is in both upper case and lower case. My server OS is linux ubuntu. apache2 php5. Linux see these as 2 different file so will not show the upper case ones. 1234.JPG What i have already is working but for lower case only, i need something to detect when the extension is in uppercase and change accordingly. This is what i have now that works for lower case only. <img src=../images/mbr_images/<?php echo H($mbr->getBarcodeNmbr());?>.jpg height=150 width=100 border=1px </img This is what i have tried but gives me a filename of "1234jpg" see the "." is missing? and is still lower case. <img src=../images/mbr_images/<?php echo H($mbr->getBarcodeNmbr()); $image = jpg; $image2 = JPG; if ($image = $image) { echo $image; } else { echo $image2; };?> height=150 width=100 border=1px </img> can anyone offer any help please? TIA Peter Hi
I am winning I think
I have got the records displayed for the current user logged in so basically they can only see their submitted listings and just working on the edit of them so the current user logged in can update their listing and is all working apart from the update of the images
the images are stored by the file name on the database and then gets moved onto the server so the actual images are not stored on the database only the file names are and the images are moved onto the server, hope that makes sense
what I can't do at the mo is work out how to update the file names of the images on the database and update on the server
I get the following error
Notice: Undefined index: photo on line 209 and line 211
the coding for them lines are below
$pic1= basename($_FILES['photo']['name'][0]); $pic2= basename($_FILES['photo']['name'][1]);The rest of the coding below that is if(!empty($_FILES['photo']['tmp_name'])) { // Number of uploaded files $num_files = count($_FILES['photo']['tmp_name']); /** loop through the array of files ***/ for($i=0; $i < $num_files;$i++) { // check if there is a file in the array if(!is_uploaded_file($_FILES['photo']['tmp_name'][$i])) { $messages[] = 'No file uploaded'; } else { // move the file to the specified dir if(move_uploaded_file($_FILES['photo']['tmp_name'][$i],$target.'/'.$_FILES['photo']['name'][$i])) { $messages[] = $_FILES['photo']['name'][$i].' uploaded'; } else { // an error message $messages[] = 'Uploading '.$_FILES['photo']['name'][$i].' Failed'; } } }The update query is below // save the data to the database mysql_query("UPDATE privatelistings SET listingtitle='$listingtitle', make='$model', model='$model', exteriorcolour='$exteriorcolour', enginesize='$enginesize', fueltype='$fueltype', yearregistered='$yearregistered', transmission='$transmission', mileage='$mileage', nodoors='$nodoors', bodystyle='$bodystyle', price='$price', photo='$pic1', photo1='$pic2' WHERE id='$id'") or die(mysql_error());I am going to be updating to mysqli just want to get it working first My HTML form coding is below <form action="" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div> <strong>Listing Title: *</strong> <input type="text" name="listingtitle" value="<?php echo $listingtitle; ?>"/> <br/> <strong>Make: *</strong> <input type="text" name="make" value="<?php echo $make; ?>"/> <br/> <strong>Model: *</strong> <input type="text" name="model" value="<?php echo $model; ?>"/> <br/> <strong>Exterior Colour: *</strong> <input type="text" name="exteriorcolour" value="<?php echo $exteriorcolour; ?>"/> <br/> <strong>Engine Size: *</strong> <input type="text" name="enginesize" value="<?php echo $enginesize; ?>"/> <br/> <strong>Fuel Type: *</strong> <input type="text" name="fueltype" value="<?php echo $fueltype; ?>"/> <br/> <strong>Year Registered: *</strong> <input type="text" name="yearregistered" value="<?php echo $yearregistered; ?>"/> <br/> <strong>Transmission: *</strong> <input type="text" name="transmission" value="<?php echo $transmission; ?>"/> <br/> <strong>Mileage: *</strong> <input type="text" name="mileage" value="<?php echo $mileage; ?>"/> <br/> <strong>Number of Doors: *</strong> <input type="text" name="nodoors" value="<?php echo $nodoors; ?>"/> <br/> <strong>Body Style: *</strong> <input type="text" name="bodystyle" value="<?php echo $bodystyle; ?>"/> <br/> <strong>Price: *</strong> <input type="text" name="price" value="<?php echo $price; ?>"/> <br/> <strong>Photo One:</strong> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br> <strong>Photo Two:</strong> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br> <input type="submit" name="submit" value="Submit"> </div> </form>sorry was not sure what other I need to show, so you guys get the idea? Hi all I am trying to write a script that takes the filename and username from a form and adds it into a mySQL database. At the moment only the username is added? Here's my code: <?php include('includes/connection.php'); $username = $_POST['username']; date_default_timezone_set('Europe/London'); // Change time zone to GMT $date = date ('D M j G:i:s'); // Set date format $path= "/home/cndvizp/public_html/prints2impress.co.uk/images/uploads/".$HTTP_POST_FILES['ufile']['name']; if($ufile !=none) { if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)) { //insert new query $filename = $_FILES['ufile']['name']; $pfw_strQuery = "INSERT INTO `uploads`(`username`,`url`,`date_entered`)VALUES (\"$username\",\"$filename\",\"$date\")" ; $pfw_result = mysql_query($pfw_strQuery); if (!$pfw_result) { die('Invalid query: ' . mysql_error()); } //include ('payment.php'); echo 'done'; } else { //include ('error.php'); echo 'error!'; exit; } } ?> Can anyone help me get the filename and the date to be added? Cheers Pete. hi to all... does anybody has an idea of parsing the filename of the textfile and its contents and insert to database.. example.. format of the filename: [date] [cod] [time] 201089 1-111 93300.txt contents of the text file: 12345 John Robinson 54321 Robert svenson the table where the information should be inserted has this fields.. name of table: logs [ID] [name] [date] Code: [Select] [time] say for example the parsing is done..it should look like this. [ID] [name] [date] [code] [time] 12345 John Robinson 2010-8-9 1-111 9:33:00 54321 Robert Svenson 2010-8-9 1-111 9:33:000 how can i do that?? can somebody help me? thanks. This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=348670.0 If it would be just CSS I would just put " " around the url, however this is a php script. Here's the line:
<li style="background: url({img server_id=$aSlidePhoto.server_id path='photo.url_photo' file=$aSlidePhoto.destination suffix='_175' title=$aSlidePhoto.title return_url=true}); width: 175px; height: 130px;">It works for all images except, for example: myimage (1).jpg What's the fix for such case? Hello, how do you search for a filename containing a date and then match it to a variable? Please note the filename may only contain some of the variable being matched to. Any help appreciated... Hi, this works: if(file_exists("myFile.txt")){etc.} this doesn't: $myFile = "myFile.txt"; if(file_exists($myFile)){etc.} Can anybody explain this to me? I'd really like to pass the filename as a variable... Kind regards, R. Hi all, I am working on my PHP script to open my emails by fetching the data from mysql database. When I open my emails I want to fetch the filename data next to `alt` in the img tag, example: what-is-bootstrap.png so I can then send the filename data to `/project/u/index` to display the images. Here is what my image will show as for example: <img src="/project/u/?id=47394f41507856374130672f6d65534430734f7177513d3d&attid=0.2&msgid=1630808059112201633&view=attachment&display=view" alt="what-is-bootstrap.png" width="452" height="302" class="gmail-a6T" tabindex="0"> Here is the index.php code:
<?php //ini_set('display_errors', 1); //ini_set('display_startup_errors', 1); //error_reporting(E_ALL); require_once "Mail.php"; require_once('Mail/IMAPv2.php'); $key = "**************"; $email_number = openssl_decrypt(hex2bin($_GET['id']),'AES-128-CBC', $key); $attach_id = $_GET['attid']; $attachment_display = $_GET['display']; $attachments = array(); $body_attachments = array(); $attachment_number = 0; $inline_number = 0; $body_number = 0; if ($attachments >= 1) { if (($attach_id == 0) or ($attach_id > 0.9)) { if($attachments[$attach_id]) { $filename = $attachments[$attach_id]['name']; $filePath = "attachments/" .$filename; if($attachment_display == 'download') { header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=".basename($filename)); echo readfile($filePath); } else if($attachment_display == 'view') { $type = 'image/jpeg'; header('Content-Type:'.$type); header('Content-Length: ' . filesize($filePath)); readfile($filePath); } } } } if ($body_attachments >= 1) { if (($attach_id >= 0.1) && ($attach_id <= 0.9)) { if ($attach_id == '0.1') { $attach_id = 0; } else if ($attach_id == '0.2') { $attach_id = 1; } else if ($attach_id == '0.3') { $attach_id = 2; } else if ($attach_id == '0.4') { $attach_id = 3; } else if ($attach_id == '0.5') { $attach_id = 4; } else if ($attach_id == '0.6') { $attach_id = 5; } else if ($attach_id == '0.7') { $attach_id = 6; } else if ($attach_id == '0.8') { $attach_id = 7; } else if ($attach_id == '0.9') { $attach_id = 8; } else if ($attach_id == '0.10') { $attach_id = 9; } else if ($attach_id == '0.11') { $attach_id = 10; } else if ($attach_id == '0.12') { $attach_id = 11; } else if ($attach_id == '0.13') { $attach_id = 12; } else if ($attach_id == '0.14') { $attach_id = 13; } else if ($attach_id == '0.15') { $attach_id = 14; } else if ($attach_id == '0.16') { $attach_id = 15; } else if ($attach_id == '0.17') { $attach_id = 16; } else if ($attach_id == '0.18') { $attach_id = 17; } else if ($attach_id == '0.19') { $attach_id = 18; } else if ($attach_id == '0.20') { $attach_id = 19; } else if ($attach_id == '0.21') { $attach_id = 20; } else if ($attach_id == '0.22') { $attach_id = 21; } else if ($attach_id == '0.23') { $attach_id = 22; } else if ($attach_id == '0.24') { $attach_id = 23; } else if ($attach_id == '0.25') { $attach_id = 24; } else if ($attach_id == '0.26') { $attach_id = 25; } else if ($attach_id == '0.27') { $attach_id = 26; } else if ($attach_id == '0.28') { $attach_id = 27; } else if ($attach_id == '0.29') { $attach_id = 28; } else if ($attach_id == '0.30') { $attach_id = 29; } if(!$body_attachments[$attach_id]) { $attach_id++; } if($body_attachments[$attach_id]) { $filename = $body_attachments[$attach_id]['name']; $filePath = "attachments/" .$filename; if($attachment_display == 'download') { header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=".basename($filename)); echo readfile($filePath); } else if($attachment_display == 'view') { $type = 'image/jpeg'; header('Content-Type:'.$type); header('Content-Length: ' . filesize($filePath)); readfile($filePath); } } } } ?>
<?php // Initialize the session session_start(); //Connect to the database include('config.php'); // Check if the user is logged in, if not then redirect him to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) { header("location: login.php"); exit; } else { $id = $_POST['email_number']; $mailfolder = $_POST['mailfolder']; $readMail = 'read'; $mailbox = $link->prepare("UPDATE " . $mailfolder . " SET readtype = ? WHERE id = ?"); $mailbox->execute([$readMail, $id]); // set the resulting array to associative $row = $mailbox->fetch(PDO::FETCH_ASSOC); if($mailbox->rowCount() == 1) { $results = array(); $mailbox_from = $row['from_email']; $mailbox_from_ = explode('<', $mailbox_from); $mailbox_from_name = $mailbox_from_[0]; $mailbox_from_email = '<' . $mailbox_from_[1]; $mailbox_from_email = htmlspecialchars($mailbox_from_email); $mailbox_to = $row['to_email']; $mailbox_to_name = $mailbox_to; $mailbox_subject = quoted_printable_decode($row['subject']); $mailbox_fulldate = $row['received_date']; $mailbox_date = convDate($mailbox_fulldate); $mailbox_message = $row['message']; $mailbox_attachment = $row['attachments']; $mailbox_folder = $_POST['folder']; $total = $_POST['total']; $email_encrypt = $row['encryption']; $send_to = $mailbox_from_email; $results['mailbox_from'] = $mailbox_from; $results['mailbox_from_'] = $mailbox_from_; $results['mailbox_from_name'] = $mailbox_from_name; $results['mailbox_from_email'] = $mailbox_from_email; $results['mailbox_to'] = htmlspecialchars($mailbox_to); $results['mailbox_subject'] = $mailbox_subject; $results['mailbox_fulldate'] = $mailbox_fulldate; $results['mailbox_date'] = $mailbox_date; $results['mailbox_message'] = $mailbox_message; $results['mailbox_attachment'] = $mailbox_attachment; $results['mailbox_folder'] = $mailbox_folder; $results['total'] = $total; $results['email_encrypt'] = $email_encrypt; $results['send_to'] = $send_to; $results['time_elapsed'] = $time_elapsed; $results['mailed_by_date'] = $mailed_by_date; $results['mailed_by'] = $mailed_by; $results['mailbox_to_name'] = $mailbox_to_name; $results['attach_test'] = $attach_test; $data = array("start"=>$start_idx,"total"=>$total,"encryption"=>$email_encrypt); $response = array("data"=>$data,"html"=>$html, "total_inbox"=>$total_inbox_unread, "total_draft"=>$total_draft_unread, "total_spam"=>$total_spam_unread, "emailBodyMessage"=>$results, "emailHeader"=>$header); echo json_encode($response); } } //Close connection $mailbox = null; ?>
I want to fetch the filename data next to `alt` so I can send the data to /project/u/index.php to display the image. Thanks in advance. |