PHP - Replace Text In Line $i
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 Similar TutorialsThe 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. what im trying to do is take a youtube embed code find the URL code for that video and remove all other parts of the code keeping only the URL of the video after i get the URL by it self then replace the http://www.youtube.com/ part of the URL with http://i2.ytimg.com/vi/ to do this i know that i need something like this to get the URL of the video http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+) but how to only return just the URL is something idk how to do then use str_replace http://www.youtube.com/(?:v|cp)/" with http://i2.ytimg.com/vi/ so in the end im asking if anyone know how to remove all other codes i dont want and only keep the URL this may have to be done using "regex" im not sure as i dont know to much about regex and what it can do but does sound like it would help lol hi, im using the following code to read the content of a file, and then add a line to the end of the file. Code: [Select] $file = dirname(dirname(dirname(__FILE__))).'/includes/settings.php'; $read = fopen($file, 'r')or die('Opening Error'); $content = fread($read, filesize($file)); fclose($read)or die('Close Error'); if(isset($_POST['cat_bg'])) { $write = fopen($file, 'w')or die('Opening Error'); $cat_bg = $_POST['cat_bg']; $new_content = $content.'$color[\'cat_header\'][\'background\'] = '.$cat_bg.';'; fwrite($write, $new_content)or die('Write Error'); fclose($write); } however i would like to delete a line from the file before the content in inserted as the new line i am inserting is a duplicate variable with a different value. Can anyone help? 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 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? 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 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 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? 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!) i have a text from the database and i want to echo just the first line , but i dont know the character = new line i tried those (to know the character) : Code: [Select] if(strpos($question['q_text'],'\n')!==false){echo 'yes';} elseif(strpos($question['q_text'],'\n')===false){echo 'no';} if(strpos($question['q_text'],'<br>')!==false){echo 'yes';} elseif(strpos($question['q_text'],'<br>')===false){echo 'no';} if(strpos($question['q_text'],'<br/>')!==false){echo 'yes';} elseif(strpos($question['q_text'],'<br/>')===false){echo 'no';} all of them are No ! how can make the text box like line as in the photo
This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=347272.0 Hi, Im trying to make a script to mass update a load of links in my database but im stuck on the basics, How can i detect a new line in a text area? Anyone know why this dosen't work? Code: [Select] <?php if($_POST[newlinks]) { $newlinks = preg_split("\n", ($_POST['newlinks'])); $i = 1; foreach ($newlinks as $newlink) { echo "$i - $newlink <br />"; $i++; } } else { echo "<form method=\"POST\" action=\"changehost.php\">"; echo "<br /> <strong>Enter the new links to try and replace old ones</strong> <br />"; echo "<textarea rows=\"16\" name=\"newlinks\" cols=\"84\"></textarea>"; echo "<input type=\"submit\" value=\"Submit\" name=\"B1\">"; ?> Hi guys, I have script which scraps content from web and writes it down in a text file, now everything seems to be okay. Its scraps and writes well but the problem is when i open that text file one weird character keeps coming after some words which i don't know about. I have attached the text file, will you guys please look at it and tell me how to replace that square looking character into new line in text file. Hi, Have a text file that is being read. I want to print the contents however I want each line of the text file to appear on a new line in the browser. So far $str = file_get_contents('records.txt'); $lines = explode("\n", $str); echo $lines[0]; Help appreciated Hi All, I am exporting data to excel, but run into a problem if the text contains a line break. When it gets to the line break, it cuts off the rest of the text. Here is my printer code: Code: [Select] $file = 'Notes_Export'; $csv_output = array(); $tmp = array(); $tmp[] = 'Created On'; $tmp[] = 'Created By'; $tmp[] = 'Note'; $csv_output[] = '"' . implode('","', $tmp) . '"'; $sql = "SELECT pn.created_on, CONCAT( u.firstname,' ', u.lastname) AS created_by, pn.note FROM prop_notes pn LEFT JOIN users u ON pn.created_by = u.user_id "; $sql .= "WHERE pn.deleted_by IS NULL AND pn.archive = '0' AND pn.property_id = '".$_GET['pid']."'"; $result = mysqli_query($connect, $sql); while($rowr = mysqli_fetch_row($result)) { $tmp = array(); for ($j=0; $j<3; $j++) {$tmp[] = $rowr[$j];} $csv_output[] = '"' . implode('","', $tmp) . '"'; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); // header( "Content-disposition: filename=".$filename.".csv"); header("Content-disposition: attachment; filename=".$filename.".csv"); print implode("\n",$csv_output) . "\n"; exit; Code: Code: [Select] PostInfo,color-main,Newman,not-collapsed;Friends,color-main2,Top Friends,not-collapsed||Twitter,color-main2,Twitter,not-collapsed;Signature,color-main2,Signature,not-collapsed;AboutMe,color-transparent,About Me,not-collapsed Now I want make a function like if PostInfo = "not-collapsed" = do this/etc, So simply, how do I extract some content out of this and then use each thing to equal to if it's 'not-collapsed' or 'collapsed' ? Very hard but i think possible? ty Hi My problem is that text that is in my database are showing up next to each other in a line rather than on seperate lines, normally I would have just used <br> but as it's generated from my sql I don't know how to do it. Code: [Select] <ul id="headlines"> <?php foreach ( $results['articles'] as $article ) { ?> <a href=".?action=viewArticle&articleId=<?php echo $article->id?>"><?php echo htmlspecialchars( $article->title )?></a> <?php } ?> </ul> Anyone have any idea? Thanks I'm ok with PHP but probably not half as good as some of you guys on here. I am basically trying to find a way to grab a line from a huge and I mean huge text file.... its basically a list of keywords I want to call by line number but without preferably going through them all before I get to that line.....otherwise couldmcrash my server obviously. At the moment im using this Code: [Select] $lines = file('http://www.mysite.com/keywords.txt'); // Loop through our array, show HTML source as HTML source; and line numbers too. foreach ($lines as $line_num => $line) { echo "$line_num"; } This works but im sure theres gotta be a better way of doing to save on usuage because this is putting the whole file into the memory and if I can simply say to php give me line number 97, would umm RULE.... Hope you guys can come up with a solution as your much smarter than me ty |