PHP - Help Needed Converting Eregi_replace Function To Preg_replace For Php 5.3
Hi,
Since upgrading to php 5.3 i have a line of code on my site that is giving me a depreciated error. The line of code is as follows: $data=eregi_replace(">"."[[:space:]]+"."<","><",$data); I've got as far as knowing i need to change it from eregi_replace to preg_replace but i can't for the life of me work out where to put any backslashes etc, if any. Is there a formula for working this type of thing out? Every example i see has backslashes and $1's all over the place. Do i simply do this "/ and this /" after and before every double quote? Or is it not as simple as that? Things never are are they! Please could an expert on here offer me any assistance. This is an important line of code(i think) so i didn't want to experiment as i would normally do, i need to get this right first time as i don't know what will happen if i get this wrong. Cheers. Similar TutorialsHi I'm trying to get rid of the deprecated functions like the eregi replace, but is currently experiancing a few problems.
I have the following function
function filterBadWords($str) { $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); $replacements = "#~"; while($row = mysql_fetch_assoc($result1)) { $str = eregi_replace($row['word'], str_repeat('#~', strlen($row['word'])), $str); } return $str; }and tried changing it into function filterBadWords($str) { $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); $replacements = "(G)"; while($row = mysql_fetch_assoc($result1)) { $str = preg_replace($row['word'], str_repeat('(G)', strlen($row['word'])), $str); } return $str; }but now I'm getting errors like preg_replace(): Delimiter must not be alphanumeric or backslash Any help regarding this? $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? Hi guys, this is what im trying to achieve, im trying to remove the links to the current page for all my web pages with a single script, like for example, if i am on a home page, then the home page hyperlink is disabled, and if i am on a about us page the hyperlink for about us is disabled, i have went through many forums and posts but the more i read the more confused i get, however i came up with a method of my own with many bits of code i've read about everywhere. firstly, the script collects the current url of the page(i dont need https or any sub direct, its just for example index.php) then it stores the page name, index.php into a variable say - $current Then a menu.php which is the navigation file is loaded and heres the part i cant get to work, i would like to match find that <a href="index.php"> index </a> and replace that with <a> index </> so that the link to the current page is disabled..i tried using preg_replace but failed miserably and opted to use str_replace Heres the code: <?php //the function below gets the current page url or file //i got this off webcheatsheet - http://www.webcheatsheet.com/PHP/get_current_page_url.php function getPage(){ return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); } //store the current url or the file name into a variable $current = getPage(); echo "The current page name is ".$current; $menu=file_get_contents("menu.php"); $string = "<a>"+$current+"</a>"; $link = "<a href="+ current +"> "; //i could not get preg_replace to work or come up with an effective regular expression //which is why i use str_replace instead. $menu=str_replace("" , $string, $menu); echo $menu; ?> Hey, I am trying to write a sort of replace function where {user:1} is converted into a set of information from a database using preg_replace. So I have created the following preg_replace: $patterns = array(); $patterns[1] = '/\{user:([0-9]+)\}/'; $replacements = array(); $replacements[1] = UserCredit('$1'); ksort($patterns); ksort($replacements); $content_show = preg_replace($patterns, $replacements, $content); echo $content_show; and then the function UserCredit which is just above that on the page: function UserCredit($user_id) { require 'connect.php'; $user_lookup = mysql_query("SELECT * FROM prop_users WHERE ID = '$user_id'"); while($row = mysql_fetch_array($user_lookup)) { $user_name = $row['full_name']; $user_file = $row['credit_file']; $user_url = $row['link_url']; $user_url_alt = $row['link_alt']; } if(mysql_num_rows($user_lookup)==0){ die("An error has occured, Sorry for any Inconvenience Caused! User ID=".$user_id); } require 'close.php'; $output = "<li class=\"clearfix\"><div class=\"credimg\"><img src=\"".$user_file."\" width=\"75px\" height=\"75px\" alt=\"".$user_name."\" /></div><p><strong><a href=\"".$user_url."\" title=\"".$user_url_alt."\">".$user_name."</a></strong><br /><em>Writing / Code</em></p></li>"; return $output; } I have tested the function and it works when I echo UserCredit('1'); And the preg_replace works at simply extracting the value for the user. The only problem is that I can't figure a way for the preg_replace to carry the value of $1 into the function it just literally carries "$1" Is there something obvious that I am missing or am I going around this the wrong way? Hi,
I'm using TCPDF to create a PDF from a webpage.
This works great but I have the following problem:
I'm building in WordPress and as you may know WP saves images on different sizes. (e.g. 150x150, 300x300 and 1024x1024)
The thing I'm trying to create is that users can download a PDF ready for printing. So High Resolution images.
I use a preg_match_all function to match the image source and remove the additional image size from the filename so the original high resolution image is loaded.
e.g. image-150x150.jpg will be replaced by image.jpg.
So now the original image that has a image size of 6024x6024px and 300 DPI is loaded.
Then TCPDF uses a resize function that resizes the image back to 150x150 px but sets the DPI to 300 so it can be printed on a good quality.
This all works but now the problem comes:
If I do the preg_match_all function the image gets "pulled" from the rest of the content and looses it's position.
So my thought to fix this was. Get a preg_replace function and replace the image tag with a function that executes the whole image change like described above.
This doesn't work......
So i'm stuck here. Hope anyone can assist me with this.
Here is what I have done so far.
function execute(){ preg_match_all("/<img[^>]+src=(?:\"|\')\K(.[^\">]+?)(?=\"|\')/",$content,$matches,PREG_PATTERN_ORDER); for( $i=0; isset($matches[1]) && $i < count($matches[1]); $i++ ) { $search = array('-'.$s1.'x'.$s2.'', '-'.$s3.'x'.$s4.'', '-'.$s5.'x'.$s6.''); $replace = array('', '', ''); $a = $matches[1][$i]; if (strpos($a,'-'.$s1.'x'.$s2.'') !== false) { $w = $s1; $w = $pdf->pixelsToUnits($w); $h = $s2; $h = $pdf->pixelsToUnits($h); $l = '57'; $l = $pdf->pixelsToUnits($l); $t = '170'; $t = $pdf->pixelsToUnits($t); }elseif (strpos($a,'-'.$s3.'x'.$s4.'') !== false) { $w = $s3; $w = $pdf->pixelsToUnits($w); $h = $s4; $h = $pdf->pixelsToUnits($h); $l = '217'; $l = $pdf->pixelsToUnits($l); $t = '20'; $t = $pdf->pixelsToUnits($t); }elseif (strpos($a,'-'.$s5.'x'.$s6.'') !== false) { $w = $s5; $w = $pdf->pixelsToUnits($w); $h = $s6; $h = $pdf->pixelsToUnits($h); $l = '57'; $l = $pdf->pixelsToUnits($l); $t = '310'; $t = $pdf->pixelsToUnits($t); } $content .= $pdf->Image(str_replace($search,$replace,$matches[1][$i]), $l, $t, $w, $h, 'JPG', '', '', true, 300, '', false, false, 0, false, false, false); } }; global $post; $id = $_GET['id']; $content_post = get_post($id);// get the content $content = $content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); $content = preg_replace('/<img[^>]+./e',execute(), $content); // replace the image tag with the new image // EXPORT IT ALL $pdf->writeHTML($content, true, false, true, false, ''); Hi, I'm trying to create a simple BB code-type function, but I'm having trouble putting a function within preg_replace. Let me show you what I mean: Code: [Select] $bb_search = array ( '/\[b\]/', '/\[\/b\]/', '/\[img\=(.*?)\]/', ); $bb_replace = array ( '<b>', '</b>', check_image( '\\1' ), ); return preg_replace( $bb_search, $bb_replace, $text_string ); The first two (b and /b) work fine, even the function is recognised, but using \\1 doesn't put the bbcode value as the function value. I know that probably made no sense - I'm terrible at explaining these things, so sorry. If anyone can understand what I mean, even offer a solution, that would be great! Cheers! I'm trying to use preg_replace but I can't get it working. function replaceContent($sContent) { $aReplaceTags = array( "'\[MENU-CARD\](.*?)\[/MENU-CARD\]'is" => '\\1', "'\[CONTACT-FORM\]'is" => "Contactform", ); return preg_replace(array_keys($aReplaceTags), array_values($aReplaceTags), $sContent); } This works great however when I change '\\1' into a function the output of '\\1' will always be 1. function replaceContent($sContent) { $aReplaceTags = array( "'\[MENU-CARD\](.*?)\[/MENU-CARD\]'is" => $this->loadMenuCard('\\1'), "'\[CONTACT-FORM\]'is" => "Contactform", ); return preg_replace(array_keys($aReplaceTags), array_values($aReplaceTags), $sContent); } Anyone knows what I am doing wrong? i get the following error in the comments in wordpress blog..: Warning: preg_replace() [function.preg-replace]: No ending delimiter '~' found in /home/doughhhh/public_html/wp-content/themes/upload/includes/theme-comments.php on line 75 the content of the file is: Code: [Select] <?php // Fist full of comments if (!function_exists("custom_comment")) { function custom_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?>> <a name="comment-<?php comment_ID() ?>"></a> <div id="li-comment-<?php comment_ID() ?>" class="comment-container"> <div class="comment-head"> <?php if(get_comment_type() == "comment"){ ?> <div class="avatar"><?php the_commenter_avatar($args) ?></div> <?php } ?> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div><!-- /.reply --> </div><!-- /.comment-head --> <div class="comment-entry" id="comment-<?php comment_ID(); ?>"> <span class="arrow"></span> <div class="comment-info"> <div class="left"><span class="name"><?php the_commenter_link() ?></span></div> <div class="right"> <span class="date"><?php echo get_comment_date(get_option( 'date_format' )) ?> <?php _e('at', 'themejunkie'); ?> <?php echo get_comment_time(get_option( 'time_format' )); ?></span> <span class="perma"><a href="<?php echo get_comment_link(); ?>" title="<?php _e('Direct link to this comment', 'themejunkie'); ?>">#</a></span> <span class="edit"><?php edit_comment_link(__('Edit', 'themejunkie'), '', ''); ?></span> </div> <div class="clear"></div> </div> <?php comment_text() ?> <?php if ($comment->comment_approved == '0') { ?> <p class='unapproved'><?php _e('Your comment is awaiting moderation.', 'themejunkie'); ?></p> <?php } ?> </div><!-- /comment-entry --> </div><!-- /.comment-container --> <?php } } // PINGBACK / TRACKBACK OUTPUT if (!function_exists("list_pings")) { function list_pings($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li id="comment-<?php comment_ID(); ?>"> <span class="author"><?php comment_author_link(); ?></span> - <span class="date"><?php echo get_comment_date(get_option( 'date_format' )) ?></span> <span class="pingcontent"><?php comment_text() ?></span> <?php } } if (!function_exists("the_commenter_link")) { function the_commenter_link() { $commenter = get_comment_author_link(); if ( preg_match( '~]* class=[^>]+>~', $commenter ) ) {$commenter = preg_replace( '~(]* class=[\'"]?)~', '\\1url ' , $commenter ); } else { $commenter = preg_replace( '~(<a )/', '\\1class="url "~' , $commenter );} echo $commenter ; } } if (!function_exists("the_commenter_avatar")) { function the_commenter_avatar($args) { $email = get_comment_author_email(); $avatar = str_replace( "class='avatar", "class='photo avatar", get_avatar( "$email", $args['avatar_size']) ); echo $avatar; } } ?> help! [attachment deleted by admin] I have this function which is javascript and I need to convert it to php.. Code: [Select] function US2dec(myUS) { if (myUS.toLowerCase() == 'even') { myUS = '100'; } var myDec; myUS = parseFloat(myUS); if (Math.abs(myUS) < 100 || isNaN(myUS)) { myDec = NaN; } else if (myUS > 0) { myDec = 1 + myUS / 100; } else { myDec = 1 - 100 / myUS; } return myDec.toFixed(8); } I came up with this php version and it seems to work but I'm no expert with math functions.. I was hoping somebody who's a bit more familiar with these functions could check it over quick.. Code: [Select] function US2dec($myUS) { if (strtolower($myUS) == 'even') { $myUS = 100; } $myDec = 0; $myUS = floatval($myUS); if (abs($myUS) < 100 || !is_numeric($myUS)) { $myDec = 0; } else if ($myUS > 0) { $myDec = 1 + $myUS / 100; } else { $myDec = 1 - 100 / $myUS; } return number_format($myDec,8); } Thanks!! I have this function completely written in my class file that I am working on. The point to this function is to be able to check the login of a user or administrator for either of the control panels associated with my site. It will check the session intime as well as the page / module referenced. Once it passes all those checks, it will check and ensure the emailaddress/password stored in the current session still holds true and the account is still active... if the account is still active it will update the lastActivity as well as update all of the session variables with what is currently in the database. What I am looking for is basically a look at the function, see if it looks good.. If there is any part to it that could create security holes for the site just off the login function itself... Usage: $q->validUser($_SESSION['user'], $_mod); <?php function validUser($sess, $p) { if ($sess['inTime'] == '' && $p != 'login' && $p != 'logout') { session_destroy(); $login = '0'; $_int = ''; return $login; } else if ($sess['inTime'] < time()-3600 && $p != 'login') { $sess['inTime'] = ''; session_destroy(); $this->check_login($sess, $p); } else { $this->user = $sess['emailAddress']; $this->pass = $sess['password']; $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); if ($login = $this->sql_numrows($login) < 1) { $sess['inTime'] == ''; session_destroy(); $login = '0'; } else { // logged in, lets update the database for last_activity AND the session. $this->sql_query("UDATE users SET lastActivity = '".now()."' WHERE emailAddress = '".$this->user."'"); $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); $login = mysql_fetch_assoc($login); foreach ($login as $key => $value) { $sess[$key] = $value; } $sess['inTime'] = time(); $login = '1'; } return $login; } } ?> That is the main function, sql_query and sql_numrows is: <?php function sql_query($query = "", $transaction = FALSE) { unset($this->query_result); if ($query != "") { $this->num_queries++; if ($transation == BEGIN_TRANSACTION && !$this->in_transation) { $result = mysql_query("BEGIN", $this->db_connect_id); if (!$result) { return false; } $this->in_transaction = TRUE; } $this->query_result = mysql_query($query, $this->db_connect_id); } else { if ($transaction == END_TRANSACTION && $this->in_transaction ) { $result = mysql_query("COMMIT", $this->db_connect_id); } } if ($this->query_result) { unset($this->row[$this->query_result]); unset($this->rowset[$this->query_result]); if ($transaction == END_TRANSACTION && $this->in_transaction ) { $this->in_transaction = FALSE; if (!mysql_query("COMMIT", $this->db_connect_id)) { mysql_query("ROLLBACK", $this->db_connect_id); return false; } } return $this->query_result; } else { if ($this->in_transaction ) { mysql_query("ROLLBACK", $this->db_connect_id); $this->in_transaction = FALSE; } return false; } } function sql_numrows($query_id = 0) { if(!$query_id) { $query_id = $this->query_result; } return ($query_id) ? mysql_num_rows($query_id) : false; } ?> Any insight that can help to benefit these functions would be appreciated. hello. im trying to write a function that sets the file path depending on what it pulls from the database i have 2 databases 1 called "templates" which has a list of template names with there id's and 1 called "basicSetting" which sets the active and default templates. in the template db i have id name type id1 = template1 admin id2 = template1 main id3 = template1 main in basic settings i have set activeAdminTemp_id = 1 defaultAdminTemp_id = 1 activeTemp_id = 2 defaultTemp_id = 2 the path should be something like this Code: [Select] include(SITE_ROOT.DS.'GET TYPE/templates/GET TEMPLATE FOLDER NAME'.DS.GET TEMPLATE NAME.php); SITE_ROOT = www.sitename.com/ GET TYPE = /admin or in the main root /templates/ = where the templates are stored GET TEMPLATE FOLDER NAME = the name of the template is the same as the folder name GET TEMPLATE NAME.php; = the name of the template.php this is what i have in my functions file Code: [Select] function include_templates(){ $tempBS = basicSettings::find_all(); //SHOULD GET THESE VALUES $tempBS->id."<br />"; $tempBS->activeAdminTemp_id."<br />"; $tempBS->defaultAdminTemp_id.'<br/>'; $tempBS->activeTemp_id.'<br/>'; $tempBS->defaultTemp_id.'<br/>'; $temp = Templates::find_all(); //SHOULD GET THESE VALUES $temp->id."<br />"; $temp->name."<br />"; $temp->type.'<br/>'; } now i need to add into my function something like this ... but im not sure. Code: [Select] $sql = "SELECT * FROM templates WHERE id='".$tempBS->id."'"; echo include(SITE_ROOT.DS.'.$temp->type./templates/'.$temp->name.''.DS.'temp->name.''.php'); but that i not working. please help thanks rick Hi there. I have a PHP Function like so: <?php function JomSocial_field($fieldcode) { $database=& JFactory::getDBO(); $user =& JFactory::getUser(); $userId = $user->get( 'id' ); $sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= '$fieldcode'"; $database->setQuery( $sql ); $fieldID = $database->loadResult(); $sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}"; $database->setQuery( $sql ); echo $database->loadResult(); } ?> I can then insert the results into form inputs like so: Code: [Select] <input type="hidden" id="enrolment_year" name="enrolment_year" value="<?php JomSocial_field("enrolment_year"); ?>" /> However, I now want to use the result in a variable like so <?php $filename1 = "folder/".print(JomSocial_field("enrolment_year"))."/file.zip"; but it doesn't work...it just actually prints the result as text on the page. The echo command doesn't work either. If it were an item that has been posted, I could get it using the $_POST["enrolment_year"], but the trouble is, I want to get the value on first page load, not after a post. Can anyone help me please? I have 3 actions below which control my cart. My problem is with the minus action. It's supposed to remove 1 quantity from the cart but instead it takes the quantity all the way down to 1. for example: you add 3 quantities of a usb stick and you want to remove 1 quantity, it would take the amount of quantity to 1 instead of 2. here are the functions: switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; header("Location: cart.php"); } else { $cart = $_GET['id']; header("Location: cart.php"); } break; case 'minus': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $item - $id; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } can some help with the minus function. thanks 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 am trying to pull out the image HTML tag but its not working as expected. Here is what I am doing $removeimagetag='/<a href/'; $replacwith = "illegal"; $_POST['descr']=preg_replace($removeimagetag,$replacwith,$_POST['descr']); in the 'descr' there is a <a href="http://s635.photobucket.com...... When it post it does not strip out the <a href So the image is displayed. I tried a modified version to test to see if it work that looked like this. $removeimagetag='/goofy/'; $replacwith = "illegal"; $_POST['descr']=preg_replace($removeimagetag,$replacwith,$_POST['descr']); When the word goofy appears in the text then its replaced with the word illegal, Also I would like to make it so that it replaces the entire line from the <a href....... to the </a> with a phrase that says "this feature is not allowed" rather than just the part in the front...the <a href. Any help you can be will be greatly appreciated. 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 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'])); } 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? & |