Unordered list in php / html

I am trying to make it so that the asterisks in my string represent list items in an unordered list.

    $first_char = substr($p,0,1);
    if($first_char == '*'){
        $p = '<ul>' . $p . '</li></ul>';
        $p = str_replace('*' , '<li>',$p);
        $p = str_replace('\n' , '</li>',$p);
    }

      

However, if it does so that no asterisks can be used as the contents of the list items. Is there a way to change this?

+3


source to share


3 answers


This may not be the best solution, but you can always skip using *

inline ( $p

). Instead, write each asterisk as its HTML equivalent, in this case &#42;

. When it is displayed in the browser, the user sees a nice star, but str_replace

shouldn't. Or you can enter some escape characters, but this can get a little complicated.



+1


source


Regex Replace Solution

<?php

$pattern = '/(?:^|\n)\s*\*[\t ]*([^\n\r]+)/';
$replacement = '<li>${1}</li>';
$count = 0;

$p = preg_replace($pattern, $replacement, $p, -1, $count);

if ($count > 0) {
    $pattern = '/(<li>.*?(?:<\/li>)(?:\s*<li>.*?(?:<\/li>))*)/';
    $replacement = '<ul>${1}</ul>';

    $p = preg_replace($pattern, $replacement, $p);
}
?>

      

Test string

* Lorem ipsum dolor sit amet, * consec*tetur adipiscing elit
    *Curabitur ullamcorper neque sit amet

 *  Pellente*sque nec quam rhoncus
Suspendisse ut lacinia arcu

* Nullam in vulpu*tate tellus

      



Output

<ul><li>Lorem ipsum dolor sit amet, * consec*tetur adipiscing elit</li>
<li>Curabitur ullamcorper neque sit amet</li>
<li>Pellentesque nec quam rhoncus</li></ul>
Suspendisse ut lacinia arcu
<ul><li>Nullam in vulputate tellus</li></ul>

      

PHP manual - preg_replace

+1


source


This is an easy way:

if(substr($p,0,1) == '*'){
    $p = '<ul>' . substr($p,1) . '</ul>;
}

      

+1


source







All Articles