1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Turning freetext numbered lists into <ol> lists with PHP

Discussion in 'PHP' started by norfstar, Jan 7, 2011.

  1. #1
    I have a database with one text field that almost always has content in numbered steps, like as follows:

    I am trying to write some PHP code that will turn that text into an HTML numbered list like as follows:

    <ol>
    <li>Do this first.</li>
    <li>Then do something else.</li>
    <li>And do something to finish.</li>
    </ol>
    Code (markup):
    Can anyone help me with this? I'm sure it's not that hard but I suck at REGEXP.
     
    norfstar, Jan 7, 2011 IP
  2. shofstetter

    shofstetter Well-Known Member

    Messages:
    178
    Likes Received:
    7
    Best Answers:
    1
    Trophy Points:
    120
    #2
    You man be able to just use explode() if the items in the fields have any common separators.

    you may find this function handy:

    
    
    function multiexplode ($delimiters,$string) {
        $ary = explode($delimiters[0],$string);
        array_shift($delimiters);
        if($delimiters != NULL) {
            foreach($ary as $key => $val) {
                 $ary[$key] = multiexplode($delimiters, $val);
            }
        }
        return  $ary;
    }
    
    
    // Example of use
    $string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
    $delimiters = Array(",",":","|","-");
    
    $res = multiexplode($delimiters,$string);
    echo '<pre>';
    print_r($res);
    echo '</pre>';
    
    
    Code (markup):
     
    shofstetter, Jan 7, 2011 IP
    norfstar likes this.
  3. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #3
    Personally I'd just perform a regular expression match to grab all of the list entries. This is untested, but I'm quite certain it should work (if not, a little tweaking and it should work):

    // Perform regular expression match
    preg_match_all( '/\d\.[\s]{0,1}(.+)[\\r\\n]{0,}/', $DbField, $Res );
    
    // Append list HTML to variable
    $Out = "<ol>\r\n";
    foreach( $Res[1] as $Val ) {
    	$Out .= "\t<li>" . $Val . "</li>\r\n";
    }
    $Out .= "</ol>";
    PHP:
    Where $DbField contains the plaintext list. Appends the HTML to variable $Out.
     
    Alex Roxon, Jan 7, 2011 IP
    norfstar likes this.
  4. norfstar

    norfstar Peon

    Messages:
    1,154
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    0
    #4

    Works perfectly! Thanks :).
     
    norfstar, Jan 10, 2011 IP