PHP - Preg_replace, Replace Text With A Function
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? Similar Tutorialsi 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 need a way of just replacing those three characters (",',\,/) with nothing, any ideas? Hi I'm trying the following code: Code: [Select] $t = '12<-- AB_C -->'; $AB_C = 'abc'; echo preg_replace('/\<-- ([A-Z_]+) --\>/', "$$1", $t);I want to get "12abc" , but it outputs: 12$AB_C , so, it not recognize the replacement as dynamic variable. Is it any way to use the matched word in preg_replace() as a variable, or dynamic variable? 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 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! 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, 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. Here are my smileys: // Here you can add additional smilies if you like (please note that you must escape single quote and backslash) $smilies = array( ':)' => 'smile.gif', ';)' => 'wink.gif', ':(' => 'sad.gif', ':mellow:' => 'mellow.gif', ':(' => 'sad.gif', ':angry:' => 'mad.gif', ':cry:' => 'cry.gif', ':banana:' => 'banana.gif', ':locked:' => 'dancinglock.gif', ':hug:' => 'hug.gif', ':bonk:' => 'bangin.gif', ':love:' => 'heart2.gif', '<3' => 'heart.gif', ':blush:' => 'blush.gif', ':p' => 'tongue.png', ':lol:' => 'lol.png', ':mad:' => 'mad.png', ':rolleyes:' => 'roll.png', ':cool:' => 'cool.png');And here is the function to convert them to images using preg_replace function do_smilies($text) { global $smilies; $text = ' '.$text.' '; foreach ($smilies as $smiley_text => $smiley_img) { if (strpos($text, $smiley_text) !== false) $text = preg_replace('%(?<=[>\s])'.preg_quote($smiley_text, '%').'(?=[^\p{L}\p{N}])%um', '<img src="/img/emoticons/'.$smiley_img.'" alt="'.$smiley_text.'">', $text); } return substr($text, 1, -1); }All of them are being replaced except for '<3', why? I tried: \<3AND <\3to see if I needed to escape the left carrot (<), but still no luck. Edited by Monkuar, 10 January 2015 - 12:19 AM. hello I've some code and I want remove text between Publisher: and >. This text is not fixed. anyone can help me to find text between two char and replace them with "" using php? thank you Hi! Basically, I'm making a PHP file that lists things from a file, so if the file contained; '@-Line 1-@@-Line 2-@' it would produce <li><a href="#">Line 1</a></li><li><a href="#">Line 2</a></li>, but I want it so it changes the coding for 1 of every 2 lines. So I've came up with this code: $myFile = "list.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, 100); fclose($fh); $oldtxt = array("@-", "-@"); $newtxt = array('<li><a href="#">','</a></li>'); $newData = str_replace($oldtxt, $newtxt, $theData); $array = explode("</li>", trim($newData)); $lineno = count($array); $linenofinal = $lineno - 1; for($i=1;$i<$linenofinal;$i++){ if(($i % 2)=='0'){ } } The bit that I'm stuck on is inside the if statement. How could I get it to replace for example <li> in line $i with <li class="1in2"> Thanks in advance, Daviga404 =D Hi, I am trying to take a string from a database and replace everything within {} with code... similar to how posting in a forum works. so say I have "...Lorem ipsom {gallery:1} sit imet..." it will take that string (from a DB) and replace "{gallery:1}" with "<?php gallery('1'); ?>". How can this be done? Or is there keywords I can search on to find the answer? Thank you in advance. I have the auto suggestion script. While the user is typing, results are printed below (from the database). The results are printed with bold letters that are in the search. However, this leads to errors in capitalization. The letters are replaced by users' queries, instead of from the database. Example: Search word: PHP Results: PHPfreaks, PHP tutorials But in the database this is the records: "phpfreaks" and "php tutorials". This is a script that replaces search letters with bolded: Code: [Select] $search = clean($_POST["search"]); $fname=$row['name']; //Record from database $re_fname='<b>'.$search.'</b>'; //Replace with bold letter $final_fname = str_ireplace($search, $re_fname, $fname); How to do a script that bold letters, but as they were in the database, not from search input? I wanted to replace a strings in a large text file .. what would be the fastest way ?! e.g the text file contains .. INSERT INTO `subjects` VALUES (1, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (2, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (3, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (4, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (5, 'some text here', 'some text here', 'some text here'); I wanted to replace the string " VALUES (1, " with "VALUES (" in each line .. I'm new in PHP so any response would be much appreciated .. thanks The title says it all,..well as all u can see, there are many methods to accomplish this done but not before undergoing through a heavy tasking process. For instance, 1. Open the file 2. Reads the content of the file into array. 3. Find out the desire line of text that we want to replace. 4. Make that line of text as variable and assigns with the new data(that we want to replace) as its values. 5.open another file. 6.Write the whole contents to the file opened in 5. 7. Put the contents back to the file of original. Can anyone contributes a better way to get this done? Like replace/delete a specific line without affecting other characters or anything therein? Thanx. P.S reading and using str_replace to make the alteration always ends up in giving some kind of result beyond desired after the first round of code execution. Hi all, hope some can help because this is giving me more grey hairs than I allready have.
I am trying to solve the following: I'm pulling in JSON data, decoding it to a array which I write to a database. However in the array are social security numbers that I don't want to store (privacyregulations). So I need to check if a row has a social security number and if it has one I want to replace it with 'anonymized'. I have got it to work successfully on a local Xampp test environment using the following script (extract off course): //first anonymize the social security number (ssn) if exists $data = json_decode($jsondata, true);
// then fill the tables foreach($data as $row) {
$insertstatement = mysqli_query($link,"INSERT INTO $tablename (personid, type, ssn) VALUES ('".$row["personid"]."', '".$row["type"]."', '".$row["ssn"]."') ON DUPLICATE KEY UPDATE type = VALUES(type), bsn = VALUES(ssn)");
This leads to a filled table where the ssn's are filled with 'anonymized' if they exist in the array and empty if it does not exist for that row. This is exactly what I want ;-).
Personid type ssn
However, when I run the same script on a Lamp production environment (lamp stack on an Azure server) it does not work. Then the scripts results in totally ignoring the whole row that contains a ssn??
Personid type ssn Hope someone can help to get this working on my production environment as well.
Richard
The situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.
For example:
<?php $str = 'some blob ~abc~ followed by ~def~'; $arr_orig = array( '~abc~', '~def~' ); $arr_new = array( 'value~def~', 'blah' ); echo str_replace( $arr_orig, $arr_new, $str ); ?>This will echo: some blob valueblah followed by blah But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need. I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!) Im dealing with html links in a database where I need to execute a small piece of php code. Well mysql doesnt execute php code thats held in a table. The easiest way for me to do this is just add the links without the code, & set up a function that will replace anything I set to for example in my case a link lookin like this: http://mysite.com/index.php?page=offers&blah=blah&sid= needs to look like this; http://mysite.com/index.php?page=offers&blah=blah&sid=<?php echo $_SESSION['login']; ?> so I would need a function like <?php $replace('sid=','sid=<?php echo $_SESSION['login'];?> ?> something like that. And I know its possible & I could create a function like this but honestly right now I am so tired after working 12 hours im lazy dont want to think to hard while I know there are a lot of people out there that have a function like this already. If you dont have one & dont feel like writing one for me could you atleast point me in the right direction so I dont have to think to hard?! Thanks!! Hi i wrote a find and replace code but my code replace last value of array and skip the first, second.... values in the array. Please give me an idea because i stack with this code. Regards $KeyWord = explode("\n", $RowGetWords['KEYWORDS']); $Replace = explode("\n", $RowGetWords['ReplaceTo']); for($i=0; $i<count($KeyWord); $i++){ $pattern = $KeyWord[$i]; $replace = "<a href=\"" .$URL. "\" target=\"_blank\" >" .$Replace[$i]. "</a>"; $html = str_replace($pattern, $replace, $Row['MessageBody']); } In the text, Code: [Select] It will eventually go away.Once the carriers merge, the combined airline, will operate as Southwest. It has its logo and colors. 2.3 AirTran brand will no longer be used. In the above text, how to replace "." with ". " and not in 2.3. how to add space after "." only if it has alphabets and not to replace after numeric characters. |