Forum Moderators: coopster
I'm having a tough problem that I want to solve with regular expressions. I'm pretty sure that it is possible for a regex to parse this thing, but since I only know the basic stuff, Im pretty much lost here.
I want to parse a string like this:
##
#list item1
#list item2
#list item3
##
And this is what I want the regex to return:
<ul>
<li>list item1</li>
<li>list item2</li>
<li>list item3</li>
</ul>
Basically, I want to parse my listing and return a valid HTML unordered list. The regex has to find start end end tags (##) and then parse the inner part to find strings like #text\n where \n is a line break.
Can anyone help me with this?
Thanks in advance!
function convert_to_list($text)
{
$pattern1 = "/(\#\#\n)((\#{1})[\w?\s?\W?\S?]+\n)*(\#\#\n)/";
$replace1 = "<ul>$2</ul>";
$list = preg_replace($pattern1, $replace1, $text);
$pattern2 = "/(\#{1})(\w{1,}.+)?\n/";
$replace2 = "<li>\\2</li>";
$text = preg_replace($pattern2, $replace2, $list);
return $text;
}
I haven't been able to get it working for multiple lists in the same piece of text... perhaps someone here is able to tweak the regex a little so it will do multiple replacements successfully?
I'm still discovering regex's myself, so it's probably not that efficient. :(
Sample regex's (regex library)
[regexlib.com...]
In depth Regex tutorial
[regular-expressions.info...]
O'reilly regex pocket reference (PDF)
[oreilly.com...]
More regex references (this is probably the best one for beginners)
[phpbuilder.com...]
#!/usr/bin/perl -w
$a=<<EOT;
##
#list item1
#list item2
#list item3
##
another list
##
#another 1
#another 2
##
EOT$a=~s{(^¦\r¦\n)
\#\#([\s\r\n]+)
((?:\#.*?[\r\n])+?)
\#\#([\r\n\s]+)
}
{ local $prefix=$1 . '<UL>' . $2;
local $suffix='</UL>' . $4;
(local $lines=$3)=~s/^#/<LI>/mg;
$prefix . $lines . $suffix;
}gsex;print $a;
As a bonus you get 'gsex' (great sex) as a regex qualifier :)
I tried to run it as a PERL script, but it didnt work. The error was: Can't find string terminator "EOT" anywhere before EOF at ./perltest line 2.
How can I get this working inside PHP's preg_replace() function?
Thanks!