PHP - Preg_replace And Paragraphs
how is it possible to allow someone to do paragraphs when using preg_replace? would someone show a few good examples of hows its done?
Similar TutorialsI've got a TEXT field in a database, that contains something like this: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tristique eros quis dui ullamcorper vulputate. Nullam cursus mollis leo nec dignissim. Suspendisse rutrum accumsan turpis, nec semper neque mattis in. Sed in eros erat, ac condimentum tortor. Donec id erat ac arcu elementum pharetra vitae sit amet odio. Donec adipiscing, enim a sagittis lacinia, justo risus pulvinar tortor, ut suscipit ligula metus eget nisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum vel purus ut metus convallis facilisis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam erat volutpat. Vestibulum id nisl pretium lectus molestie semper. Quisque augue lorem, adipiscing ac varius vitae, hendrerit sit amet metus. Phasellus hendrerit sagittis nisl ac tincidunt." However, when I display this data using PHP is does not differentiate between the linebreak and a space, so the displayed text looks like this: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tristique eros quis dui ullamcorper vulputate. Nullam cursus mollis leo nec dignissim. Suspendisse rutrum accumsan turpis, nec semper neque mattis in. Sed in eros erat, ac condimentum tortor. Donec id erat ac arcu elementum pharetra vitae sit amet odio. Donec adipiscing, enim a sagittis lacinia, justo risus pulvinar tortor, ut suscipit ligula metus eget nisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum vel purus ut metus convallis facilisis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam erat volutpat. Vestibulum id nisl pretium lectus molestie semper. Quisque augue lorem, adipiscing ac varius vitae, hendrerit sit amet metus. Phasellus hendrerit sagittis nisl ac tincidunt." How can I keep a paragraph as a paragraph using MySQL and PHP?? Hi guys, I am very simply inserting text into a table with php and mysql, and outputting it, it all works fine but when I use paragraphs when inserting it, and then try to ouput it, all the paragraphs are gone and it looks like one big block of text, I suppose the way to go around this is to use <br> instead of just enters as it probably doesnt read this, but is it possible to make this text area do read and insert <br>'s where people use enter to make paragraphs? Much help appreciated, I realize this must be a very beginner question but I am not really sure how to word this so I wasn't sure on specific search on this. hello guys, suppose I want to echo out the text given below exactly as what has been set against, including the line breaks. How do I do it? coz each time i did it so, there s no line breaks but the output is usually a dense lump of words with no paragraphs. Code: [Select] I took her out it was a Friday night I wore cologne to get the feeling right We started making out and she took off my pants But then I turned on the TV And that's about the time she walked away from me Nobody likes you when you're 23 I'm still more amused by TV shows What the hell is ADD? My friends say I should act my age What's my age again? What's my age again? please help P.S. The whole set of phrase give above are treated as a single variable coz I use a WHILE loops when making an echo. tthanks Hi there, I got some good advice from Harristweed the other day about how to export from Mysql to excel, so that each field appears in a different column in excel. I expanded the code Harristweed gave me to cover all fields in my database, and all went well until the 2nd last field, when I hit a brick wall. Unlike previous fields, which were based on info inputted via radio buttons, dropdown lists, or text boxes, the field causing problems was based on data that came from a text area on the web form. A few tests revealed that the problem was related to when a user pressed the "Enter" key while filling in that field, to begin a new paragraph. When this happens, it would go into the database fine. However, when I used the code to export it to excel, anything after the "Enter" key had been pressed would appear in a new cell on a new row, thereby putting the table out of alignment. I could get around this by rewording the question into a few questions which each use a text box rather than a text area box. However, if there is a way to get around this by tweaking the php code, I'd love to know. The field with which I'm having the problem is the one called "experience". Thanks for your time, Dave <?PHP $db = mysql_connect("localhost", "MYUSERNAME", "MYPASSWORD"); mysql_select_db("MYDATABASE",$db); $query="SELECT * FROM applications2010"; $result=mysql_query($query); $header=" date\t firstname\t lastname\t sex\t dobday\t dobmonth\t dobyear\t streetaddress\t suburb\t state\t postcode\t country\t preferredphone\t secondphone\t thirdphone\t emailaddress\t emconname\t emconphone\t experience\t "; while($row = mysql_fetch_assoc($result)) { if(empty($row[date]))$row[date]=" "; if(empty($row[firstname]))$row[firstname]=" "; if(empty($row[lastname]))$row[lastname]=" "; if(empty($row[sex]))$row[sex]=" "; if(empty($row[dobday]))$row[dobday]=" "; if(empty($row[dobmonth]))$row[dobmonth]=" "; if(empty($row[dobyear]))$row[dobyear]=" "; if(empty($row[streetaddress]))$row[streetaddress]=" "; if(empty($row[suburb]))$row[suburb]=" "; if(empty($row[state]))$row[state]=" "; if(empty($row[postcode]))$row[postcode]=" "; if(empty($row[country]))$row[country]=" "; if(empty($row[preferredphone]))$row[preferredphone]=" "; if(empty($row[secondphone]))$row[secondphone]=" "; if(empty($row[thirdphone]))$row[thirdphone]=" "; if(empty($row[emailaddress]))$row[emailaddress]=" "; if(empty($row[emconname]))$row[emconname]=" "; if(empty($row[emconphone]))$row[emconphone]=" "; if(empty($row[experience]))$row[experience]=" "; $line = ''; $line .= "$row[date]\t $row[firstname]\t $row[lastname]\t $row[sex]\t $row[dobday]\t $row[dobmonth]\t $row[dobyear]\t $row[streetaddress]\t $row[suburb]\t $row[state]\t $row[postcode]\t $row[country]\t $row[preferredphone]\t $row[secondphone]\t $row[thirdphone]\t $row[emailaddress]\t $row[emconname]\t $row[emconphone]\t $row[experience]\t "; $data .= trim($line)."\n"; } $data = str_replace("\r","",$data); if ($data == "") { $data = "\n(0) Records Found!\n"; } header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=filename=".date("d-m-Y")."-export.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data";exit; ?> I want to remove empty paragraphs from an HTML document using simple_html_dom.php. I know how to do it using the DOMDocument class, but, because the HTML files I work with are prepared in MS Word, the DOMDocument's loadHTMLFile() function gives this exception "Namespaces are not defined". This is the code I use with the DOMDocument object for HTML files not prepared in MS Word: <?php /* Using the DOMDocument class */ /* Create a new DOMDocument object. */ $html = new DOMDocument("1.0", "UTF-8"); /* Load HTML code from an HTML file into the DOMDocument. */ $html->loadHTMLFile("HTML File With Empty Paragraphs.html"); /* Assign all the <p> elements into the $pars DOMNodeList object. */ $pars = $html->getElementsByTagName("p"); echo "The initial number of paragraphs is " . $pars->length . ".<br />"; /* The trim() function is used to remove leading and trailing spaces as well as * newline characters. */ for ($i = 0; $i < $pars->length; $i++){ if (trim($pars->item($i)->textContent) == ""){ $pars->item($i)->parentNode->removeChild($pars->item($i)); $i--; } } echo "The final number of paragraphs is " . $pars->length . ".<br />"; // Write the HTML code back into an HTML file. $html->saveHTMLFile("HTML File WithOut Empty Paragraphs.html"); ?> This is the code I use with the simple_html_dom.php module for HTML files prepared in MS Word: <?php /* Using simple_html_dom.php */ include("simple_html_dom.php"); $html = file_get_html("HTML File With Empty Paragraphs.html"); $pars = $html->find("p"); for ($i = 0; $i < count($pars); $i++) { if (trim($pars[$i]->plaintext) == "") { unset($pars[$i]); $i--; } } $html->save("HTML File without Empty Paragraphs.html"); ?> It is almost the same, except that that the $pars variable is a DOMNodeList when using DOMDocument and an array when using simple_html_dom.php. But this code does not work. First it runs for two minutes and then reports these errors: "Undefined offset: 1" and "Trying to get property of nonobject" for this line: "if (trim($pars[$i]->plaintext == "")) {". Does anyone know how I can fix this? Thank you. I also asked on stackoverflow. I currently have some custom tags, similar to BBCode, to be used for comments on my site. I'm trying to create a [nobr] tag (note: I know the no break tag will work in many major browsers, but it's deprecated, so I'm trying to be compliant). The idea is that if I encounter the [nobr] tag, I need to remove all line breaks. Here's the best I can do, but it's not working as I had hoped. Here's what I currently use to replace line breaks with a break tag. Code: [Select] $str=str_replace("\r\n","<br>",$str); Here's my attempt at introducing this new tag. Code: [Select] function BbToHtml($str) { $before=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\1",$str); $during=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\2",$str); $after=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\3",$str); $during=str_replace("\r\n","",$during); if($during != "") { // If the [nobr] tag was found, go with the new string. $str = $before.$during.$after; } else { // If the [nobr] tag was not found, go ahead like normal. $str=str_replace("\r\n","<br>",$str); } return $str; I can't get that working. Any ideas on how to fix that, or a completely alternate method of doing it? Thank you! After days of searching I found this thread http://www.phpfreaks.com/forums/index.php?topic=236954.0 that helped me do what I was trying to do. I've gotten the code to create and rename my html document but I can't figure out how to use the preg_replace part. This is my template with the 3 variables I want to replace with values from a form. Code: [Select] <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <?php include_once('content.php') ?> </body> <SCRIPT language="JavaScript" SRC="javascript.js"></SCRIPT> <script type="text/javascript"> function nametitle(){ parent.iframe1.document.getElementById("div1").innerHTML = "VARIABLE1 <br>VARIABLE2"; parent.iframe1.document.getElementById("quotes").innerHTML = "VARIABLE3"; } </script> </html> I've spent hours reading and trying to understand how to make it work but it's a little over my head. Could someone help me with this? Thanks, Hello ppl, I have this website link http://www.somesite.com/anotherpage/yetotherpage.html what i want to make is using preg_replace that the final result will be www.somesite.com 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? & 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 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'm trying to search a string for all occurences of a pattern, then append text after that pattern. The example is:
SUM("foo") as "bar"
and have it display as:
SUM("foo") over() as "bar"
The "SUM" could be any SQL aggregate and be case insensitive. So For bonus points, let's say the valid aggregates are array('SUM', 'MAX', 'MIN', 'AVG'). My plan right now is to figure it out for SUM, then loop it replacing the aggregate.
This is what I have so far... and it is not working.
$l= 'SUM("foo") as "bar"';
$l=preg_replace('/([^"]+")/','\0 over()',$l);
Thanks,
Ryan
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? Hi there! I need to echo some text from a database table, this text should be linked to a url stored in the same database. I am trying to do this with preg_replace but I am terrible at it! I keep getting this error: Warning: Wrong parameter count for preg_replace() while($row = mysql_fetch_array( $result )) { $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; echo preg_replace ($reg_exUrl, $row['title'); Any suggestion? Thanks This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=347057.0 This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=350441.0 $titleurl = preg_replace('/[^a-zA-Z0-9_ -%]/', '-', $d); $titleurl = preg_replace('/[ ]/', '-', $titleurl); How do you add to this to replace ---- with - --- with - -- with - and remove quotes? How do you remove a - if it's at the very end of $titleurl. For example, replace My-iPhone- with My-iPhone Okay, i know there are lots of these questions out there and tons of ways to do this. I do have it working to replace URLs with <a href="URLs">URLs</a> but now i need some help detecting <a href=""></a> so the preg_replace will not double up the code and mess up the link. here is my code so far. Code: [Select] <?php echo 'COMMENTS<br /><br />'; while($rows = mysql_fetch_array($comres)){ list($comid, $menu_title, $post_id, $comdate, $comname, $comment) = $rows; $comment = nl2br($comment); $comment = preg_replace('/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/', '<a href="$0" target="_new">$0</a>', $comment); $comment = str_replace("´", "'", $comment); $comdate = date("g:ia - M j, Y",strtotime("$comdate")); echo 'User: '.$comname.'<font color="#B20303"> - '.$comdate.'</font><br />'; echo ' - '.$comment.'<br /><br />'; } ?> so with this code, if someone commented a link like this http://example.com it will turn it this <a href="http://example.com" target="_new">http://example.com</a> but now if someone knew some basic HTML coding, and they used this <a href="http://example.com">Example.com</a> it will look like this... <a href=<a href="http://example.com" target="_new">http://example.com</a>>Example.com</a> How come preg_replace won't traverse multiple lines?
<?php
$str = ' |