PHP - Preg_replace Php Code Issue
im working on a php syntax highlighter for a bbeditor. basically all text within code tags will be placed into the function parse_code().
It works fine until i add the code to instantiate a class within the tags. This is supposed to just be a string but it looks like the 'e' modifier of preg_replace is recognising the code as php and executing it. Is there any way around this? Heres the regex: Code: [Select] '|\[code=(.*?)\](.*?)\[\/code\]|sie', 'self::parse_code("\\1", "\\2")', and the parse_code method public static function parse_code($code, $content) { $words = explode(' ', $content); dump($words); $keywords = array( 'php_words' => array( 'function', 'echo', 'class', 'new', ), ); foreach($words as $key => $value) { foreach($keywords as $group => $array) { foreach($array as $keyword) { $words[$key] = preg_replace('|'.$keyword.'|si', '<span class="'.$group.'">'.$keyword.'</span>', $words[$key]); } } $words[$key] = preg_replace("|\\'(.*?)\\'|si", '<span class="string">\'\\1\'</span>', $words[$key]); } $content = implode(' ', $words); $lines = explode("\n", $content); unset($lines[0]); for($i=1; $i<count($lines); $i++) { $lines[$i] = '<p class="line_number">'.$i.'. </p>'.$lines[$i]; } $content = implode("\n", $lines); return stripslashes('<blockquote class="code"><div class="code_header"><p>'.$code.'</p></div><div class="code_content"><p>'.$content.'</p></div></blockquote>'); } Similar Tutorialsim not sure how to do this: my code used the deprecated ereg_replace like this: $name = ereg_replace(" ", "", $name); i replaced it with this: $name = preg_replace(" ", "", $name); //this is line 65 but know get a warning: Warning: preg_replace(): Empty regular expression on line 65 what am i doing wrong please? thank you The code snippet below works fine with PHP 5.3 (register_globals = Off) but does NOT give the same results with PHP 5.5: $verhash = md5($tstamp."salt"); if ($hash != $verhash) { $_SESSION['direct'] = 1; if(isset($_SESSION['ntrd'])) { unset($_SESSION['ntrd']); } if(isset($_SESSION['rntr'])) { unset($_SESSION['rntr']); } header('refresh: 0; url=/accessDenied.php'); exit; }I'm not sure if there is a problem with the above snippet or with some other part of the code but I always get redirected to the 'accessDenied.php' page with PHP 5.5. Can someone tell me if the snippet above would output differently on PHP 5.5? Thanks, Jeff Edited by jeffshead, 04 November 2014 - 08:36 PM. ok, I thought I had this working but I guess not. Once I click the submit button the email goes but I need to be redirected to a web page named http://myserver/notification_sent.php I edited the line: <form method="post"> to look like <form method="post" action="http://myserver/notification_sent.php"> & I then get redirected to the page I need but the email don't go out. Code: [Select] $mailheaders = "From: Reporting System<rps@yahoo.org>"; $destination = array(); if (!empty($_POST['notify_jane'])) $destination[] = 'email1@yahoo.org'; if (!empty($_POST['notify_john'])) $destination[] = 'email2@yahoo.org'; if ($destination) { mail(join(', ', $destination), 'Document Added/Updated', 'This is a test notification', $mailheaders); } ?> <form method="post"> <input type="hidden" name="formsent" value="true" /> <br/> If you do not need to send a notification to someone you can close this window. If you do, choose the name(s) below and click submit. <br/>------------------------------------------------------- <br/>Check this box <input autocomplete="off" type="checkbox" name="notify_jane" value="yes" /> to send <strong>John Doe</strong> a notification. <br/>Check this box <input autocomplete="off" type="checkbox" name="notify_jane" value="yes" /> to send <strong>Jane Doe</strong> a notification. <br> <br> <input type="submit" value="Submit" /> <br/>------------------------------------------------------- </form> <?php Can someone take a look at line 36 in this code? This code pulls data from a MySQL database & displays it in a form. Then I can edit the data & click submit & it updates the MySQL database. It then, sends an email to the email address on line 35. Again, all of this works until I start editing line 36 to send the location, first name, & last name within the message of the email. What is the code so I can get an email with the first name, last name & location? Code: [Select] <?php # edit_dqa.php $page_title = 'Edit a Record'; $con = mysql_connect("localhost","uname","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("psrflow", $con); if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { $id = $_GET['id']; } elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form has been submitted. $id = $_POST['id']; } else { // No valid ID, kill the script. echo '<h1 id="mainhead">Page Error</h1> <p class="error">This page has been accessed in error.</p><p><br /><br /></p>'; include ('./includes/footer.html'); exit(); } $query = "UPDATE psrinfo SET fname='$fn', lname='$ln', location='$loc' WHERE fid=$id"; $result = @mysql_query ($query); // Run the query. // Send Email switch ('location') { case 'location1': echo $EmailAddress = 'myemail@yahoo.com'; break; } $EmailAddress = 'myemail@yahoo.com'; $Message = "Someone has edited the information below."; Location : {$_REQUEST['location']}<br>First Name : {$_REQUEST['fname']}<br>Last Name : {$_REQUEST['lname']}" $Headers = "MIME-Version: 1.0\n"; $Headers = "Content-type: text/html; charset=iso-8859-1\n"; $Subject = "Please Change"; $Headers = "To: DQA <$EmailAddress>\n"; $Headers = "From: anotheremail@yahoo.com \n"; if (mail($EmailAddress, $Subject, $Message, $Headers)) { $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); if ((substr($url, -1) == '/') OR (substr($url, -1) == '//')) { $url = substr ($url, 0, -1); } $url ='/flow/index.html'; header("Location: $url"); exit(); } else { // Report the errors. echo '<h1 id="mainhead">Error!</h1> <p class="error">The following error(s) occurred:<br />'; foreach ($errors as $msg) { // Print each error. echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p><p><br /></p>'; } // End of if (empty($errors)) IF. } // End of submit conditional. // Retrieve the user's information. $query = "SELECT pacts, fname, lname, location WHERE fid = " . $_REQUEST['id']; $result = @mysql_query ($query); // Run the query. if (mysql_num_rows($result) == 1) { // Valid user ID, show the form. $row = mysql_fetch_array ($result, MYSQL_NUM); ?> <?php echo '<form action="edit_dqa.php" method="post"> <fieldset><legend><h1> You are editing a record!</h1></legend> <b>First Name:</b> <br><input type="text" name="fname" size="15" maxlength="30" value="'.$row[1].'" /><br /> <b>Last Name:</b> <br><input type="text" name="lname" size="15" maxlength="30" value="'.$row[2].'" /><br /> <b>Location: </b><br><input type="text" name="location" size="15" maxlength="30" value="'.$row[5].'" /><br> br> <br> </fieldset> <div align="left"><input type="submit" name="submit" value="Submit" /></div> <input type="hidden" name="submitted" value="TRUE" /> <input type="hidden" name="id" value="' . $id . '" /> </form>'; } else { // Not a valid user ID. echo '<h1 id="mainhead">Page Error</h1> <p class="error">This page has been accessed in error.</p><p><br /><br /></p>'; } mysql_close(); // Close the database connection. ?> I have a pretty basic PHP log in code connected to a database of register users. However, it's not allowing any users to enter? Could someone please review the code and let me know if you find any errors? //Create query $qry="SELECT * FROM customers WHERE username='$login' AND password='".md5($_POST['password'])."'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { //Login Successful session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['id']; $_SESSION['SESS_FIRST_NAME'] = $member['fname']; $_SESSION['SESS_LAST_NAME'] = $member['lname']; session_write_close(); header("location: key_catalog.php"); exit(); }else { //Login failed header("location: login-failed.php"); exit(); } }else { die("Query failed"); } ?> I have this working code except I can't redirect to a thank you page when a new user registers. When they login it works without issue. I just don't know where or what to put for the registration part.
Here is my Code. Any help would be much appreciated.
<?php This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=320820.0 Is there a performance or security issue when embedding HTML code to be written to a page using a series of ECHO statements within PHP? Here's two examples: <?php // Some PHP code echo "<p>Hello, World</p>\n"; // More php code ?> versus: <?php> // Some PHP script commands ?> <p>Hello World\n"; <?php // More PHP code ?> Is there a performance issue or potential security flaw that would make the first example any worse/better than the second? (Is one method more "secure" than the other method, I guess is what I'm asking?) I like the ease of just throwing in HTML within a PHP script without having toe escape quote marks, etc. But, I'm a bit concerned about security since whatever technique I use will be incorporated into a "commercial" production website. Hi y'all. I just inherited a legacy system that is in mid-rebuild but needs to be tended until it can be completely phased out and have run into an issue I can't remember how to deal with. The file system is as such: DocumentRoot/ m/ js/ css/ In the 'm' directory I have many files that use require_once as so: require_once "m/another_file.php"; The problem is that none of them have a $_SERVER['DOCUMENT_ROOT'] or even a __DIR__ to start the path, so I'm blowing up with errors. I know this code works as it's currently in production, but I can't remember for the life of me what php.ini or .htaccess setting needs to be set to make it viable. My coworker swears he didn't have to do any magic to make it work on his system. Anybody old enough to remember? Edited June 25, 2020 by maxxdHello everyone, I begin in everything web related but I have been programming for years. I tried to code something simple : small Mysql DB (works fine) and to begin a search bar to browse data. I adapted a code that I understood provided here : https://www.cloudways.com/blog/live-search-php-mysql-ajax/. Base principle is simple : as you type in your query, it will pass the text to script.js that will forward this request to ajax.php file. In the ajax.php, a javascript function named “fill()” will pass the fetched results. This function will also display the result(s) into “display” div in the “search.php” file. The problem is that when I type anything it displays, below the search bar, at the moment I type a character: Quote
'; //Fetching result from database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?> ")'>
instead of the actual answer from my database (no error in the browser console). I tested the SQL query + the user I provide and everything seems fine. Any clue what could be the root cause ? I strongly suspect a mistake in the code as I already corrected one (script.js instead of scripts.js) but I really cannot figure out where. Thanks in advance,
problematic code (ajax.php):
<?php //Including Database configuration file. include "db.php"; //Getting value of "search" variable from "script.js". if (isset($_POST['search'])) { //Search box value assigning to $Name variable. $Name = $_POST['search']; //Search query. $Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5"; //Query execution $ExecQuery = MySQLi_query($con, $Query); //Creating unordered list to display result. echo ' <ul> '; //Fetching result from database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?> <!-- Creating unordered list items. Calling javascript function named as "fill" found in "script.js" file. By passing fetched result as parameter. --> <li onclick='fill("<?php echo $Result['Name']; ?>")'> <a> <!-- Assigning searched result in "Search box" in "search.php" file. --> <?php echo $Result['Name']; ?> </li></a> <!-- Below php code is just for closing parenthesis. Don't be confused. --> <?php }} ?> </ul>
My Error Output is this: Warning: Cannot modify header information - headers already sent by (output started at city-search.php:1) in city-search.php on line 65 What I'm I missing in the code, I can't seem to get these. It works excellent in Localhost, but in production. Error above. Code: [Select] <?php // MG CREATED THIS SIMPLE REGISTRATION PHP FOR THAT GOES TO ONE SPECIFIC USER. // WILL TEST FORM REGSITRATION NG 07-2011 //If the form is submitted if(isset($_POST['submit'])) { //Check to make sure that the name field is not empty if(trim($_POST['name']) == '') { $hasError = true; } else { $name = trim($_POST['name']); } //Check to make sure that the subject field is not empty if(trim($_POST['subject']) == '') { $hasError = true; } else { $subject = trim($_POST['subject']); } //Check to make sure sure that a valid email address is submitted if(trim($_POST['email']) == '') { $hasError = true; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) { $hasError = true; } else { $email = trim($_POST['email']); } //Check to make sure comments were entered if(trim($_POST['message']) == '') { //$hasError = true; $comments == 'Have No Friends'; } else { if(function_exists('stripslashes')) { $comments = stripslashes(trim($_POST['message'])); } else { $comments = trim($_POST['message']); } } //If there is no error, send the email if(!isset($hasError)) { //$emailTo = 'regina@shushmedeals.com'; //$emailTo = 'reginabyrd32@yahoo.com'; $emailTo = 'mp3@danjaproduction.com'; //$emailBcc = 'ganja99@netzero.net'; //$emailBcc = 'info@danjaproduction.com'; //$emailBcc = 'ganja99@netzero.net'; //Put your own email address here $body = "Location: $name \n\nEmail: $email \n\nShushMeDeals Sign-up Info:\n $comments"; // To send HTML mail, the Content-type header must be set $headers = 'From: ShushMeDeals.com City Location sign-up - '.$name.'' . "\r\n" . 'Reply-To: ' . $email . "\r\n" .'Bcc: print@extremeatlanta.com'; //$headers .= 'Cc: birthdayarchive@example.com' . "\r\n"; //$headers .= 'Bcc: info@danjaproduction.com' . "\r\n"; mail($emailTo, $subject, $body, $headers); $emailSent = true; if($emailSent = true) { setcookie("location", $name); //echo '<script type="text/javascript"> // window.location = "index.php?option=com_enmasse&controller=deal&task=today&locationName='.$name.'" // </script>'; } } } ?> im trying to do a complex(i think) prg replace but i keep getting the error: Code: [Select] Failed evaluating code: $lang->showing-1,1 the code i am trying to replace is: Code: [Select] <asf: lang[showing-<asf: var[num_report_alerts]>,<asf: var[num_report_alerts]>]> and the preg_replace is: Code: [Select] $content = preg_replace('|\<asf: lang\[(.*?)-(.*?)\]\>|e', '$lang->replace_vars($lang->//1, array(\\2))', $content); its supposed to take everything inside <asf: lang[]> and echo \\1 which would be "showing" and then add \\2 into an array which would be "array(1,1)". So the output would be showing 1 of 1. Anyone know where im going wrong? I'm trying to search a string for all occurences of a pattern, then append text after that pattern. The example is:
SUM("foo") as "bar"
and have it display as:
SUM("foo") over() as "bar"
The "SUM" could be any SQL aggregate and be case insensitive. So For bonus points, let's say the valid aggregates are array('SUM', 'MAX', 'MIN', 'AVG'). My plan right now is to figure it out for SUM, then loop it replacing the aggregate.
This is what I have so far... and it is not working.
$l= 'SUM("foo") as "bar"';
$l=preg_replace('/([^"]+")/','\0 over()',$l);
Thanks,
Ryan
Hi everyone, how do i add and ampersand symbol into preg_replace preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/" where do i place the symbol? & Hi there! I need to echo some text from a database table, this text should be linked to a url stored in the same database. I am trying to do this with preg_replace but I am terrible at it! I keep getting this error: Warning: Wrong parameter count for preg_replace() while($row = mysql_fetch_array( $result )) { $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; echo preg_replace ($reg_exUrl, $row['title'); Any suggestion? Thanks I currently have some custom tags, similar to BBCode, to be used for comments on my site. I'm trying to create a [nobr] tag (note: I know the no break tag will work in many major browsers, but it's deprecated, so I'm trying to be compliant). The idea is that if I encounter the [nobr] tag, I need to remove all line breaks. Here's the best I can do, but it's not working as I had hoped. Here's what I currently use to replace line breaks with a break tag. Code: [Select] $str=str_replace("\r\n","<br>",$str); Here's my attempt at introducing this new tag. Code: [Select] function BbToHtml($str) { $before=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\1",$str); $during=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\2",$str); $after=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\3",$str); $during=str_replace("\r\n","",$during); if($during != "") { // If the [nobr] tag was found, go with the new string. $str = $before.$during.$after; } else { // If the [nobr] tag was not found, go ahead like normal. $str=str_replace("\r\n","<br>",$str); } return $str; I can't get that working. Any ideas on how to fix that, or a completely alternate method of doing it? Thank you! Hi, I'm kind of new to PHP and very new to Regular Expressions and I was wondering if someone could help run through this code snippet from a callback function in a Joomla plugin called Affliates Feed. So far I have this is passed a pointer to variable item (I understand this is effectively the same as passing the variable but a lot less CPU intensive. Creates an array with keys and values Now the for loop I am stuck with, I understand the interation through the array. But what is preg_replace returning and why pass it back that way hasn't it already done its job? Can any one help? And please feel free to be as basic as possible :help: Thanks, Adam Code: [Select] function gardening(&$item) { #renaming categories, not the most efficient use for example strtolower first, and use only lowercase in the rename array $rename=array( ' Gardening?' => '', 'Climber Plants' => 'Climbing Plants', 'Seeds.*Bulbs' => 'Seeds Bulbs', 'Plant protection' => 'Horticultural goods', 'Garden structures' => 'Garden buildings',); foreach ( $rename as $k => $v ) { list($item['menu_1'],$item['menu_2'])=preg_replace("#$k#",$v,array($item['menu_1'],$item['menu_2'])); } $item['menu_1']=ucfirst(strtolower($item['menu_1'])); $item['menu_2']=ucfirst(strtolower($item['menu_2'])); $item['menu_3']=ucfirst(strtolower($item['menu_3'])); $item['menu_4']=ucfirst(strtolower($item['menu_4'])); } i have: $msg = ereg_replace("[^A-z0-9]"," ",$msg); $msg = ereg_replace(" "," ",$msg); $msg = ereg_replace(" "," ",$msg); how will i apply preg_replace please??? thank you After days of searching I found this thread http://www.phpfreaks.com/forums/index.php?topic=236954.0 that helped me do what I was trying to do. I've gotten the code to create and rename my html document but I can't figure out how to use the preg_replace part. This is my template with the 3 variables I want to replace with values from a form. Code: [Select] <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <?php include_once('content.php') ?> </body> <SCRIPT language="JavaScript" SRC="javascript.js"></SCRIPT> <script type="text/javascript"> function nametitle(){ parent.iframe1.document.getElementById("div1").innerHTML = "VARIABLE1 <br>VARIABLE2"; parent.iframe1.document.getElementById("quotes").innerHTML = "VARIABLE3"; } </script> </html> I've spent hours reading and trying to understand how to make it work but it's a little over my head. Could someone help me with this? Thanks, Hello ppl, I have this website link http://www.somesite.com/anotherpage/yetotherpage.html what i want to make is using preg_replace that the final result will be www.somesite.com |