View Full Version : Preg help...

09-05-2005, 07:44 PM
Hey. I am having trouble with a preg function.

$text = preg_replace('#(\n*)(.+)(\n*)#i', '<p>$2</p>'."\n", str_replace("\r\n", "\n", $text));

I use that for a news system I am working on. What is does is convert all line breaks to paragraph tags and because of that, it is meant for conent that needs little line brakes, such as news. However, if I were to use the <pre> tag in the content being processed, such as
echo "blah";

it would turn it into
<p>echo "blah";</p>

Making huge gaps. I am wondering how I can ignore text that is inside a <pre> tag from being processed into a bunch of paragrahs. I was thinking using regex in the code I already have above, but i'm not sure how to do it. Can anyone help?

09-06-2005, 02:20 AM
Regex really is one of my weak points, but try something like this (after running your original regexp:

function replace_paragraph($m)
$st = str_replace('<p>', '', $m[3]);
return '<pre>'.str_replace('</p>', '', $st).'</pre>';

$text = preg_replace_callback("/(\<p\>?)(\<pre\>(.+?)\<\/pre\>(\<\/p\>?))/is", 'replace_paragraph', $text);

09-06-2005, 02:29 AM
Well, it's not only for <pre> tags. Stuff like <ul>, <ol>, <li>, etc need to work. Someone else made a suggestion about usig assertions, and it would be easy to include the other tags also...

09-06-2005, 02:31 AM
so if i understand correctly, the system should accept any HTML? If thats the case then why not require the user to put in <p> tages themselves.?

09-06-2005, 02:55 AM
Not any HTML, limited. Basically the ones maentioned in this topic and a few extra.

I don't want to tell the users to put the <p> tags there themselves. While they will have a choise whether to use allowed HTML or not, the <p> tags are mandatory. It's a bit complicated, but in short: I can't expect them to put it there.

09-06-2005, 02:57 AM
It sounds like you would be better off with a BBCODE system, similar to what this board uses... That way, people who know nothing about HTML wont get confused when the < and > cause problems in some cases.

09-06-2005, 03:13 AM
Nope. I come from a message board that uses regular HTML, albeit it is only the non harmfull ones, like bold and italic. Board member are familiar with basic HTML and since all of the people that are going to be using this come from the message board, they won't get confused. I made it specifically for the users at the message board. v_v

I need it to be like I described. I've tried numorous things with no luck.