简体   繁体   中英

Unordered list in Php/HTML

I am trying to make it so that asterisks in my string denote list elements 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 this makes it so that no asterisks can be used as content in the list elements. Is there any way to change this?

This may not be the best solution but you could always not use * in the string ( $p ). Instead, write every asterisk as its HTML code equivalent, in this case &#42; . When shown in a browser, user sees nice asterisk but str_replace should not see it. Or you could introduce some escaping characters, but that may get a bit complicated.

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

This is the simple way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM