3

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?

Andrew Hu
  • 113
  • 1
  • 8
  • Perhaps you could use a combination of characters to denote a list item. Not sure how relevant this might be to your situation, but have a look at Markdown. It's is a good text to HTML converter. – Petet May 01 '15 at 23:24
  • One thing you could do is a combination of your php (to create the list items like you are doing above) and then convert the `li` nodes into asterisks using the `content` property in css. what I wrote below wasn't really an *answer* to your direct question, so I deleted it. If you want to look into this, there's some useful information here: http://stackoverflow.com/a/12216973/3044080 – nomistic May 02 '15 at 00:06

3 Answers3

2

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

HandyDan
  • 425
  • 2
  • 8
1

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.

NoroSlivka
  • 29
  • 4
1

This is the simple way:

if(substr($p,0,1) == '*'){
    $p = '<ul>' . substr($p,1) . '</ul>;
}
Misunderstood
  • 5,534
  • 1
  • 18
  • 25