PHP - Preg_match_all And Add Slashes Help
Hi there i have this code:
Code: [Select] $str = "<i><font color="800080"> man </font></i><p><font color="9898989"> hi </font></p><p><font color="1111111"> cheers </font></p>"; $pattern = '/<font .*?>(.*?)<\/font>/'; if(preg_match_all($pattern, addslashes($str), $posts)){ $i=0; for($i; $i < count($posts[0]); $i++){ echo "content: " . $posts[0][$i] . "<br/>"; echo "colour: " . $posts[1][$i] . "<br/>"; echo "<br />"; } } and it doesn't work apparently because of the addslashes but its really needed as double quotes needs to be escaped, consider that i'm applying this code to a larger html file with hundreds of double quotes to be escaped.... error msg i get is Parse error: syntax error, unexpected T_LNUMBER in thanks in advance.. Similar TutorialsHello again, I have some form data, which I then search through for particular code data like so: $html2 = $_POST['fname']; preg_match_all("/<bla>(.*)<\/bla>/", $html2, $matches40); So the above searches for all the data between <bla>XXXXXX</bla> from $POST Which I then print to my page using: (Only so I can see while developing) print_r($matches40); This displays HTML output like so: Code: [Select] Array ( [0] => Array ( [0] => Hello [1] => My [2] => Name [3] => Is [4] => Tom ) [1] => Array ( [0] => Hello [1] => My [2] => Name [3] => Is [4] => Tom ) ) What I am trying to do is again use the preg_match_all function to look through the array output and find data that I want to remove. E.g. If one of the variables from $matches40 is 'Tom' I want to find and replaces this with 'Ben'. I spent a day searching Google but to not success. Any help? Hi: Is this the proper way to remove slashes from apostrophes: Code: [Select] if ($_SERVER['REQUEST_METHOD'] == 'POST') { $myTitle = mysql_real_escape_string(stripslashes($_POST['myTitle'])); $myDesc = mysql_real_escape_string(stripslashes($_POST['myDesc'])); $myHeader = mysql_real_escape_string(stripslashes($_POST['myHeader'])); $mySubHeader = mysql_real_escape_string(stripslashes($_POST['mySubHeader'])); $myPageData = mysql_real_escape_string(stripslashes($_POST['myPageData'])); It seems to work fine, I'd just like to clarify I'm not missing anything. Thanks! Hello Everyone, I've been working with XAMPP 1.7.3 and have a general question. I've always read (and been told) to use addslashes() for any MySQL input to protect the database. My PHP.ini file has magic quotes off and the system automatically produces a caret symbol "^" in front of every control character I upload to the database. I can't find anything in the PHP.ini file relating to the caret symbols and control characters, nor can I find anything in the My.ini file. In testing, it the system behaves just as it would if I had magic quotes on, except that the system uses the carets instead of slashes. I have no problem removing the carets (and any slashes that a user might upload) but would like to know what is going on. I've done google searches on this and have only found content regarding regular expressions. Could someone clue me in? Thank in advance. Cheers, Rick Hi All I Am confused I would like to put info into a database but need it to be secure. I have some code shown below. The problem is I would like to put in ' but keep the data secure. When it comes back I do not want to show \' I think you might know what I am trying to do. Here is the code but would like to know how to stop the \' showing. Code: [Select] $password = mysql_real_escape_string(stripslashes(trim($_POST['password']))); Any help would be great thank you. i want to find the text between "{:" and ":}", may be 1 or more instances of this i'm using this php: $str = "hello {:first_name:} ha, this is {:awesome:} haha"; $do = preg_match_all("/{:(.*):}/", $str, $matches); which works if theres just one instance, but when you use more than 1 instance (like the above example) it returns: first_name:} ha, this is {:awesome But i want it to return a value of first_name, AND a separate value of "awesome" ideas? thanks This is driving me nuts and I'm hoping someone can help me figure it out. I have a site with PHP/MySQL. I have a form where people can submit a comment. This comment then goes into a MySQL database and gets displayed back on another page of the website. NOTE: I put this question in the PHP Forum because I think the problem is happening somewhere BEFORE the info gets entered into MySQL. But of course, I could be wrong. The problem is that some of the comments are coming in with a "\" in front of apostropes, but NOT ALL OF THEM (which is really confusing me). For example, someone entered this comment which shows in the MySQL database exactly like this... I predict Lena's gonna win a lifetime Grammy. It's long overdue. Someone else entered a comment which shows in the MySQL database exactly like this... can\\\'t wait to see first pics of the next addition. Congrats! They both have apostrophes in them, but only that second one added those slashes (and 3 of them for some reason). There are more instances of this where some comments have the slashes before the apostrophe and some don't. Anyone know what might be causing this seemingly random insertion of slashes? Ok so I'm coding up a file tree for a script and I've got the system setup so that when a user clicks on a folder it adds that folder to the path. The path is stored in a variable, but I'd like to allow the user to be able to go down multiple directories at once. To do this I'm going to seperate each folder name in the path and link to it so as an example: $path = './home/public_html/folder1/folder2'; how can I separate each of those so I can make a link to that folder so that: /home goes to $path = './home/'; /public_html goes to $path = './home/public_html'; etc... --- Basically just seperate the slashes into an array and seperate each of them off based on how far along it is but I don't know how to do that... Hi guys When I insert a data into MySQL and thru addslashes() it is adding not one but 3 slashes in mysql. By the way here are the codes, Code: [Select] <?php //$conn = new mysqli('localhost', 'root', '', 'my_db'); $conn = new mysqli('localhost', 'coder9_work', '******', 'coder9_portfolio'); $query = "INSERT into portfolio(category, title, description, version, started, finished) VALUES (?, ?, ?, ?, ?, ?)"; $select = $_POST['select']; $title = addslashes($_POST['title']); $description = $_POST['description']; $version = $_POST['version']; $started = $_POST['started']; $finished = $_POST['finished']; $stmt = $conn->stmt_init(); if($stmt->prepare($query)) { $stmt->bind_param('ssssss', $select, $title, $description, $version, $started, $finished); $stmt->execute(); } if($stmt) { echo "Thank you!"; } else { echo "There was a problem. Please try again later."; } ?> How do I fix this problem so that It will add only one slashes? Thanks in advanced. I have this page that keeps adding slashes (exponentially) to the $sql var that gets passed on through the hidden text area. I cannot figure out why it does this. Any ideas are appreciated. Thank you. <?php include_once $_SERVER['DOCUMENT_ROOT'] . '/include/login.php'; include_once $_SERVER['DOCUMENT_ROOT'] . '/include/mysql.php'; if(!Login::loggedIn()) { include $_SERVER['DOCUMENT_ROOT'] . '/include/uploads/pages/login.php'; } else { function displayForm() { $sql = 'SELECT * FROM `content` WHERE `contentCallid` = \'' . $_GET['page'] . '\''; $con = $GLOBALS['mysql']->connect(); $query = mysql_query($sql, $con); $content = mysql_fetch_array($query); $content['breadcrumb'] = explode(',', $content['breadcrumb']); $content['breadcrumbLink'] = explode(',', $content['breadcrumbLink']); $breadcrumb = ''; for($i = 0; $i < count($content['breadcrumb']); $i++) { if($i > 0) $breadcrumb .= ','; $breadcrumb .= $content['breadcrumbLink'][$i] . '::' . $content['breadcrumb'][$i]; } if(empty($_POST['sql'])) { $sql = 'INSERT INTO `contentVersions` (`contentCallid` , `contentTitle` , `content` , `views` , `permissionNeeded` , `status` , `version` , `created` , `createdBy` , `lastEdit` , `lastEditBy` , `breadcrumb` , `breadcrumbLink` , `noBreadcrumb` ) VALUES ( \'' . ($content['contentCallid']) . '\', \'' . ($content['contentTitle']) . '\', \'' . ($content['content']) . '\', \'' . ($content['views']) . '\', \'' . ($content['permissionNeeded']) . '\', \'' . ($content['status']) . '\', \'' . ($content['version']) . '\', \'' . ($content['created']) . '\', \'' . ($content['createdBy']) . '\', \'' . ($content['lastEdit']) . '\', \'' . ($content['lastEditBy']) . '\', \'' . ($content['breadcrumb']) . '\', \'' . ($content['breadcrumbLink']) . '\', \'' . ($content['noBreadcrumb']) . '\');'; $sql = stripslashes($sql); } else { $sql = $_POST['sql']; } ?> <form id="loginForm" name="loginForm" method="post" action="index.php?p=editPage&page=<?= $_GET['page']; ?>&ref=editPage"> <fieldset> <legend>Page Settings </legend> <p> <label>Page Title: </label> <input name="title" style="width:450px;" id="title" value="<?= $content['contentTitle']; ?>" type="text" /> </p> <p> <label>Content ID: </label> <input name="callid" readonly="readonly" style="width:381px;" id="callid" value="<?= $content['contentCallid']; ?>" type="text" /> <input name="suggestC" type="button" value="Suggest" onclick="suggestCallID('<?= $content['contentCallid']; ?>');" /> </p> <p> <label>Breadcrumb: </label> <input name="breadcrumb" style="width:381px;" id="breadcrumb" value="<?= $breadcrumb; ?>" type="text" /> <input name="suggestBC" type="button" value="Suggest" onclick="suggestBreadcrumb();" /></p> </fieldset> <textarea name="editPageWYS" id="editPageWYS"><?= $content['content']; ?></textarea> <textarea style="visibility:hidden;" name="sql"><?= $sql; ?></textarea> <textarea style="visibility:hidden;" name="version"><?= $content['version']; ?></textarea> <textarea style="visibility:hidden;" name="contentid"><?= $content['contentid']; ?></textarea> <fieldset> <legend>Actions</legend> <p> <input name="save" type="submit" value="Save" /> </p> </fieldset> </form> <?php } if(!empty($_POST['save'])) { if(empty($_POST['title']) || empty($_POST['callid'])) { echo '<blockquote class="failure">Save not successful. You need to have both a title and content id. Please type in a title then click the "Suggest" button.</blockquote>'; displayForm(); } else { $time = time(); $bc = explode(',', $_POST['breadcrumb']); $bcText = array(); $bcLink = array(); for($i = 0; $i < count($bc); $i++) { $bc[$i] = explode('::', $bc[$i]); $bcLink[$i] = $bc[$i][0]; $bcText[$i] = $bc[$i][1]; } $bcLink = implode(',', $bcLink); $bcText = implode(',', $bcText); $con = $GLOBALS['mysql']->connect(); $query = mysql_query($_POST['sql'], $con); echo $_POST['sql']; if(!$query) { echo '<blockquote class="failure">Warning: A MySQL error has occured while adding the backup to the database.<p>' . mysql_error() . '</p></blockquote>'; displayForm(); } $sql = 'UPDATE `content` SET `content` = \'' . $_POST['editPageWYS'] . '\', `breadcrumb` = \'' . $bcText . '\', `breadcrumbLink` = \'' . $bcLink . '\', `contentCallid` = \'' . $_POST['callid'] . '\', `contentTitle` = \'' . $_POST['title'] . '\', `version` = \'' . ($_POST['version'] + 1) . '\', `lastEdit` = \'' . $time . '\', `lastEditBy` = \'' . $_SESSION['username'] . '\' WHERE `contentid` = ' . $_POST['contentid'] . ' LIMIT 1 ;'; $query = mysql_query($sql, $con); if(!$query) { echo '<blockquote class="failure">MySQL Error<p>' . mysql_error() . '</p></blockquote>'; displayForm(); } else { echo '<blockquote>Page Successfully Edited<br /><br /><a href="index.php?p=' . $_POST['callid'] . '&ref=newPage">Click Here to View It</a></blockquote>'; } } } else { displayForm(); } } ?> I am trying to use preg_match_all to find some information on a webpage. Here is what I am currently using <?php $homepage = "http://www.example.com"; $page_contents1 = file_get_contents($homepage); $names1 = preg_match_all('/<span class="video_date">(.*)</span> - <a class="b" href="/(.*)/">(.*)</a><br/>\/', $page_contents1, $matches1); echo implode(", ", $matches1[1]); ?> I am trying to match this piece of html: <span class="video_date">Oct 21</span> - <a class="b" href="/meanwhilezealand/"> Meanwhile in New Zealand...</a><br/> Thanks for looking! This is rather bothering as I know if you use the delimiter / regex pattern s it should ignore newlines preg_match_all("%<p><b>(.*?)</b>%s", $html, $data); Returns a blank array the page data is like so <p> <b>41,910</b><br/> Total Points </p> Never had a problem before that i can recall but for some reason with this page it's giving me issues. Maybe i'm missing something? I have noticed that if I run the preg_match_all function and use PREG_OFFSET_CAPTURE option to start capture somwhere in the middle of the string the second half of the string will be searched first returning the matching sections along with positions, then it goes up to the top half and returns matches from there too. Is there way to parse only between start point and end of string? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=348635.0 Hello all! So I am working on screen scraping a site for my son's rec league. I seem to be having problem with the pre_match_all syntax. Here is my code Code: [Select] <?php $url = "http://www.mywebsite.com"; $raw = file_get_contents($url); $newlines = array("\t","\n","\r","\x20\x20","\0","\x0B"); $content = str_replace($newlines, "", html_entity_decode($raw)); $start = strpos($content,'table border="1" cellpadding="1" cellspacing="0"'); $end = strpos($content,'</table>',$start) + 8; $table = substr($content,$start,$end-$start); preg_match_all("|<tr(.*)</tr>|U",$table,$rows); foreach ($rows[0] as $row){ if ((strpos($row,'<th')===false)){ preg_match_all("|<td(.*)</td>|U",$row,$cells); $game_date = strip_tags($cells[0][0]); $game_time = strip_tags($cells[0][1]); $rink = strip_tags($cells[0][2]); $home_team = strip_tags($cells[0][3]); $home_score = strip_tags($cells[0][4]); $visiting_team = strip_tags($cells[0][5]); $visiting_score = strip_tags($cells[0][6]); echo "{$game_date} @ {$game_time} : [{$home_team}] - {$home_score} vs. [{$visiting_team}] - {$visiting_score} <br>\n"; } } ?> My issue is that I am trying to get it to only display the data if the team name = x. I tried to replace the preg_match_all("|<td(.*)</td>|U",$row,$cells); with preg_match_all("|Posse|U",$row,$cells); (Posse is one of the team names). No luck. Any input/thoughts?! Thank you!! This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=328802.0 Hi all, I've been having some trouble with the whole slashes and apostrophy situation. When the user enters into the database locally they can enter in apostophies no problem and it outputs on the site no problem. When the user edits the data it then alters it and removes apostrophies from the headline field, not the text editor field (tinyMCE). However, when I test it on the web (it's secured so I am unable to provide a link), there are more problems, those being that when it enters into the database it adds slashes where there are apostrophies but doesn't do this locally... Could this by a PHP version issue? Version 5.3.5 on the web and 5.3.1 locally. In addition when the you come to edit the data all of the apostropies and following letter have been removed and slashes put in their place. But as I say this doesn't happen locally.. Here is the insert statement: <?php require_once('auth.php'); ?> <?php $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $newsHeadline = $_POST['newsHeadline']; $newsContent = $_POST['newsContent']; $query = "INSERT INTO news (newsDate, newsHeadline, newsContent) VALUES ('".date("l"." "."j"." "."F"." "."Y")."','".mysql_real_escape_string($newsHeadline)."','".mysql_real_escape_string($newsContent)."')"; if(mysql_query($query)) { echo "News successfully inserted.<br/><a href='addNews.php'>Back to main page</a><br/>"; }else echo "Encountered an error.".mysql_error()."<a href='javascript:history.go(-1)'>Click here to go back</a><br/>"; // close connection mysql_close(); ?> Here is the php to output the text // while there are rows to be fetched... while ($list = mysql_fetch_assoc($resultSelectNewsData)) { // echo data echo "<div class='newsArticle'><p class='newsHeadline'>"; echo stripslashes ($list['newsHeadline']); echo "<br /><span class='nDate'>Posted on: ".$list['newsDate']."</span></p><div class='newsContent'><p>"; echo stripslashes ($list['newsContent']); echo "</p></div><!--news content end--><br /></div><!--news article end-->"; } // end while Here is the PHP to view the data ready to edit: <?php require_once('auth.php'); ?> <?php $pagetitle = "Langbaurgh Sunday League";?> <?php include("includesAdmin/header.php");?> <?php include("includesAdmin/nav.php");?> <div id="mainContentAdmin"> <h1>Admin Panel</h1> <?php // Make a MySQL Connection $newsID=$_GET['newsID']; //Query to join tables and obtain team names linked to IDs $sql2= mysql_query ("SELECT * FROM news WHERE newsID = '$newsID'")or die(mysql_error()); echo "<form name='editDetails' method='post' action='php_update_news_item.php'>"; $row = mysql_fetch_array($sql2); // Print out the contents of each row echo "<input type='hidden' name='newsID' id='newsID' size='15' value='".$row['newsID']."'/>"; echo"News Headine: <br /><input type='text' name='newsHeadline' id='newsHeadline' size='40' value='".$row['newsHeadline']."'/><br />"; echo"News Story: <br /><textarea name='newsContent' id='newsContent' cols='50' rows='15'>".$row['newsContent']."</textarea>"; echo "<input type='submit' name='submit' value='Update News Story'/>"; mysql_close(); ?> </div><!--contentAreaEnd--> <?php include("includesAdmin/footer.php");?> Here is the file to update the data <?php require_once('auth.php'); ?> <?php $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $newsID = $_POST['newsID']; $newsHeadline = $_POST['newsHeadline']; $newsContent = $_POST['newsContent']; $query = "UPDATE news SET newsHeadline='".mysql_real_escape_string($newsHeadline)."', newsContent='".mysql_real_escape_string($newsContent)."' WHERE newsID='".mysql_real_escape_string($newsID)."'"; if(mysql_query($query)) { echo "News successfully updated.<br/><a href='view_news_id.php'>Back to news viewing</a><br/>"; }else echo "Encountered an error.".mysql_error()."<a href='javascript:history.go(-1)'>Click here to go back</a><br/>"; // close connection mysql_close(); ?> All help would be massively appreciated as I am really stuck with this. I've tried all sorts including stripslashes, trim, a combination of both, yet I hit snags with each one of them.. Many thanks in advance, Aidan Hi everyone I am trying to secure some of my code using a sanitize function function sanitize($data) { $cdata = strip_tags(addslashes($data)); $cdata = mysql_real_escape_string($cdata); return $cdata; } If I post a form value such as Code: [Select] 'Apple iPod' to a SQL INSERT QUERY using `title` = sanitize($_POST['title']); then my database value looks like Code: [Select] \\\'the ipod\\\' this is odd because there is 3 slashes if I then print that value on a PHP page using print stripslashes($row['title']); it outputs Code: [Select] \'the ipod\' Why can I not get rid of the slashes and why would it be outputting 3 slashes? I have tried all the magic quote ideas and suggestions, but still cannot sort this out. Thanks John Hi, I need to analyze a string and get the text between, before, and after the forward slashes.. The string will always look something like this, but will vary: $str = "I will go to the store with <# one/two/three #> people." Then I need to create a form with radio buttons for each choice. In this case (one, two, or three). The text between the <# ... #> could be different every time, and with uknown amount of forward slashes. Here is what I have so far but it doesn't work. Code to find if there are slashes: Code: [Select] preg_match_all( '/([/]+)/',$str,$matches); Code to create html form .. Code: [Select] $i = 0; $html = '<form>'; foreach ($matches[0] as $match){ if ($pos = strpos( $str,$match ) ) === false ) continue; } $html .= '<input type="radio" name="place-' . $i . '" value=". $match . '" /> '; } $html .= '</form>'; Its not working as needed. I'm not sure how to create radio button choices for the words (one, two, three). Thanks i have a php form where users can update db. but when the input has a <a href=""></a> input, it generates back slashes on the web. below is the results after the input. Code: [Select] <a href=\'\\\"images/gallery/storyslideshow/ppic-5 (1).jpg\'\\\" rel=\'\\\"lyteshow[featgallery]\'\\\" title=\'\\\"\'\\\">View Slideshow</a><br><br> i have a this on my updating code Code: [Select] mysql_real_escape_string($_POST["fulldesc"]); |