December 22nd, 2011, 04:13 AM
RegEx - adding <ol> to a list
I have a number of HTML lists that need a <ol> and </ol> at the beginning and end. The problem is the list length, (the number of <li>__LINK__</li> ) differs from cell to cell - I am using Excel to hold the formatted data for each record.
I am thinking I need to find the first <li> and replace with <ol><li> and the last </li> and replace with </li></ol>
My regex skill aren't up to scratch so any help is greatly appreciated.
December 22nd, 2011, 08:23 AM
Show some example data. Is there really ONE first <li> and ONE last </li>? If so, that's very easy.
HEY! YOU! Read the New User Guide and Forum Rules
"They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin
"The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002
Think we're being rude? Maybe you asked a bad question
or you're a Help Vampire.
Trying to argue intelligently? Please read this.
December 22nd, 2011, 02:12 PM
As ManiacDan was saying, seeing sample data always helps write the expression.
In the meantime, if I understood your requirements, this code might work.
A. Replacing the first <li>
It's a simple preg_replace on a multiple-line string, case insensitive.
$result = preg_replace('/(?is)<li>/', '<ol><li>', $string,1);
The key here is the last argument: the 1 says "make one replacement then stop".
B. Replacing the last </li>
Here we don't need the "1". Because of the greedy star, the regex engine shoots all the way to the end of the string, then backtracks to match the very last </li>
$result = preg_replace('%(?is).*</li>%', '</li></ol>', $string);
The i and s modes are turned on inline but you could turn them on after the pattern string if you prefer.
I haven't tested those but am hopeful that I didn't introduce a bug of some kind. Give it a whirl and let me know how you go, happy to help you tweak it if it doesn't do the job.