PHP - How To Replace String With Name Or Image
hello again need some advice
cant get it working Code: [Select] SELECT * FROM `tsue_members` WHERE memberid=0 if ($row['memberid'] == '0') { $img = "1.gif"; } echo $img; Similar TutorialsThe 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!) Hi - newbie to php - I need to search a string and possibly replace part of it. This is how I would do it in perl: Code: [Select] if ($homepage) { if ($homepage !~ /http/i) { $homepage = "http:\/\/" . $homepage; } } I have a homepage field in the database but sometimes people put the http in, and sometimes they leave it out. In perl I can figure it out and format accordingly but it doesn't work in PHP. I'm not sure if the first line even works in PHP. Maybe if to say something like: if $homepage is not equal to nothing. I'm not sure. Any help would be appreciated. Thanks. Hi Guys I'm sure this is really simple for you experts but it's proving to be my nemesis! I have an array of words: eg. $words = array('Apples','Bananas','Cherries'); and would like to search a string of text for these words and create link tags around them based on a simple template, <a href="#">$word_found</a> $text = "I love eating apples and bananas but hate cherries!"; So i would like to return a string like this: $text = "I love eating <a href=#>apples</a> and <a href="#">bananas</a> but hate <a href="#">cherries!</a>"; Now, I need it to do a case insensitive search, but just wrap tags around the words it finds, leaving the case as it was found in the string. I want to avoid using a function where I have to list all the replacements like this: function replace_text($text){ $replace = array('apples' => '<a href="#">apples</a>','bananas' => '<a href="#">bananas</a>'); $text = str_ireplace(array_keys($replace), $replace, $text); return $text; } because it seems very messy and long winded. Also it's not case insensitive. It seems like there must be a way of simply searching for the words in my array and wrapping tags around the found words. Please can anyone help!? Many Thanks Dan How can I replace the comma from a string like this: You, like this => You like this You, Derp, like this => You and Derp like this You, Derp, Derpina, like this => You, Derp and Derpina like this You, Derp, Derpina, Derpson, like this => You, Derp, Derpina and Derpison like this Hello All, I've been knocking my head against the wall for several hours trying to figure out what's going on with a simple string replace. For the most part it is working beautifully, but if a string contains a similar but not exact match it still replaces the non match. I was under the impression that str_replace always looks for an exact match. I have custom tags that are in strings of text that are structured like: [A_CUSTOM_HEADER] [A_CUSTOM_TITLE] and so on. They always start with "[A_CUSTOM" and end with a " ] ". In between the start and end can be just about anything. So my problem is if I have [A_CUSTOM] and [A_CUSTOM_TAG] in the same text str_replace seems to incorrectly replace all the [A_CUSTOM_TAG] with the [A_CUSTOM] content and the match never happens for the [A_CUSTOM_TAG] content. For example: $content = 'Here is some text and [A_CUSTOM]. Here is more text and [A_CUSTOM_TAG]'. $content = str_replace('[A_CUSTOM]','I have a and custom',$content); $content = str_replace('[A_CUSTOM_TAG]','I have a, custom and tag',$content);So running that code The [A_CUSTOM_TAG] content never gets replaced correctly, it is replaced on the first pass with the [A_CUSTOM] replacement content. I hope this make sense I'm trying to explain it the best I can. I tried using preg_replace() with \b to match the whole word but didn't get anything close to the respected results...haha I'm sure I'm missing something simple...or at least I hope I am. Thanks in advance! Edited by Twitch, 22 May 2014 - 11:52 AM. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=319445.0 May I please ask one more question? About replacing a string only if it appears *after* a particular string?
I'm having trouble replacing all occurrences of "wheel" with "TIRE" but only when the word "wheel" is after this: (W/
Example:
From this:
A large wheel is shiny.
Big 4 wheel truck (W/ wheel)
Car with a wheel, and a small toy (w/ wheel)
Four wheelers are cool
To this:
A large wheel is shiny.
Big 4 wheel truck (W/ TIRE)
Car with a wheel, and a small toy (w/ TIRE)
Four wheelers are cool
Unfortunately, I thought this worked:
$fixed = str_ireplace('wheel','tire',substr($original_string,stripos($original_string,'(W')));
...until I realized it was *cutting off* all characters up until that first '(W/'
What can be done to make this work?
Edited by Nyla, 20 November 2014 - 09:40 PM. 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. hey guys just a simple one...im trying to replace {$name} but i dont think ive got the right prefix in the str_replace function...if anyone could tell me where i am going wrong please $content = str_replace("{/$".$variable."}", $value, $content); {$name} 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 I embed videos on my site. I submit the embed codes to my database using a form. The codes look like this:
<iframe width="560" height="315" src="//www.youtube.com/embed/xDIgbjDGsOM?rel=0" frameborder="0" allowfullscreen></iframe>Before I submit each code, I have to change its width and height, and I have to add this: &showinfo=0after this: ?rel=0Is there a function that will allow me to do all of that simultaneously? I know about str_ireplace(). It will let me replace ?rel=0 with ?rel=0&showinfo=0, but I don't know how to simultaneously make the other changes. It's not helping that the embed code includes quotation marks. I've managed to insert an image in my database, but when i upload a second picture it replaces the first!What should i do? Hi. I have a script here that will let users upload an image to my website but I just can't figure out how to save the uploaded image as "upload/logo.png" so that it will replace the already existing "upload/logo.png". Help would be greatly appreciated. Code: [Select] <html> <body> <form action="" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> <?php if(isset($_POST['submit']) && !empty($_FILES["file"]["name"])) { $timestamp = time(); $target = "upload/"; $target = $target . basename($_FILES['uploaded']['name']) ; $ok=1; $allowed_types = array("image/gif","image/jpeg","image/pjpeg","image/png","image/bmp"); $allowed_extensions = array("gif","png","jpg","bmp"); if ($_FILES['file']['size'] > 350000) { $max_size = round(350000 / 1024); echo "Your file is too large. Maximum $max_size Kb is allowed. <br>"; $ok=0; } if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; $ok=0; } else { $path_parts = pathinfo(strtolower($_FILES["file"]["name"])); if(in_array($_FILES["file"]["type"],$allowed_types) && in_array($path_parts["extension"],$allowed_extensions)){ $filename = $timestamp."-".$_FILES["file"]["name"]; echo "Name: " . $filename . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; $path_parts = pathinfo($_FILES["file"]["name"]); echo "Extension: " . $path_parts["extension"] . "<br />"; echo "Size: " . round($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Stored in: " . $_FILES["file"]["tmp_name"]. " <br />"; } else { echo "Type " . $_FILES["file"]["type"] . " with extension " . $path_parts["extension"] . " not allowed <br />"; $ok=0; } } if($ok == 1){ @move_uploaded_file($_FILES["file"]["tmp_name"], $target . $filename); $file_location = $target . $filename; if(file_exists($file_location)){ echo "Uploaded to <a href='$file_location'>$filename</a> <br />"; } else { echo "There was a problem saving the file. <br />"; } } } else { echo "Select your file to upload."; } ?> Thanks! Hey I have a string that looks like the following: Quote top-php-tutorials-2.html I have a script that cycles through each page. The 2 in the quote above is the page number. How can I extract the number between the - and the .html and replace it with another number? I've tried Code: [Select] substr($engine->selectedcaturl, 0,-6).$v.".html"But then I realised this only works for numbers that are 1 digit long Any input would be appreciated 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']); } i want to be able to extract a string from a variable when an IMG tag is present and then use the link of the image to create an image tag of it's own to be displayed let's say i have a string $post which contains the following... (ignoring the quotations) here is some random text ["IMG"]http://www.somedomain.com/someimage.jpg[/"IMG"] here is some more random text how would i be able to extract the string inside the [IMG] tags and replace it with a different string in the same position excluding the [IMG] tags such as <img src=''http://www.somedomain.com/someimage.jpg"/> any recommendations on how i would be able to do this? Hi group, I need to create a string to be used by base64_encode to build an SVG file. The source for the string is an image I built in memory. Code: [Select] $img = imagecreatetruecolor( 50,50 ); Other stuff, draw circles, test, ect. I currently write it out to disk with: Code: [Select] imagepng( $img, "$Name.png" ); Then read it back in and process it to create an SVG file. I would like to avoid writing it to disk, so how can I create a string for base64_encode from an in memory image?? Thanks for your time. Hi.. I am relatively new. I am trying to show an image link in my code below: $image = "<img src=<imgpg/" . $part_no . ".JPG />"; <td class = "guide_body" width = "66%"></td><td align = "center"><?php echo $image;?> There is more code but these are the problem lines I believe. Both are within the php environment.
This is producing:
It is supposed to look like this: So it is adding %3C for some reason between localhost and imgpg directory. I have no idea why this is happening. Is there something I can do to prevent this from happening? Or is there something I can do to erase the extra characters. (I'm not sure if they might be different though at some point. I have the same problem both on my local computer and the remote server.) Thanks very much for any help!! Hello, I am attempting to create a script where a user puts a text string into a form and clicking on submit. Then it adds that text string to a mysql database and gives the user a link back to it. Something like mysite.com/key.php?id=4 and when going to that link it will display the text string from the database but printed in an image. I wrote something up but I cannot get it to work. I may be a little in over my head. Any help is appreciated.
The way I coded this all to work is the user inputs the information into index.php which givekey.php inserts that into the database. I have not yet figure out how to do this in one single step. After that I wanted it to navigate directly to key.php which would display the key and the link to that page with the ?key=XX attribute. getkey.php <?php require_once 'dbinfo.php'; // database connection $id = $_GET['id']; // do some validation here to ensure id is safe $link = mysql_connect($servername, $username, $password); if (!$link) { die('Could not connect: ' . mysql_error()); } @mysql_select_db($database) or die( "Unable to select database"); $sql = "SELECT ukey FROM keycode WHERE id=$id"; $result = mysql_query("$sql"); $row = mysql_fetch_assoc($result); mysql_close($link); header("Content-type: image/png"); echo $row['ukey']; ?> key.php <html> <head> <title>Your Key Is Ready</title> </head> <body> <img src="getkey.php?id=1" width="175" height="200" /> </body> </html>index.php <html> <head> <title></title> </head> <body> <section id="mid_section"> <div id="boxes"> <h1> Testing input key </h1> <br/> <form id="myform" action="givekey.php" method="post"> Key:<br /> <input type="text" value="ukey"> Source:<br /> <input type="radio" value="hb">HB<br /> <input type="radio" value="ig">IG<br /> <input type="radio" value="other">Other<br /> <button id="sub">Submit</button> </form> </body> </html>givekey.php <?php include_once('dbinfo.php'); $conn = mysql_connect($servername, $username, $password); $db= mysql_select_db($database); $ukey =$_POST['ukey']; $hb =$_POST['hb']; $ig =$_POST['ig']; $other =$_POST['other']; if(mysql_query("INSERT INTO `keycode`(`ukey`) VALUES ([$ukey]); INSERT INTO `source`(`hb`,`ig`,`other`) VALUES ([$hb],[$ig],[$other]);")) ?> Edited by chrisb302, 13 November 2014 - 12:18 AM. |