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?

2
  • 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. Commented May 1, 2015 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: stackoverflow.com/a/12216973/3044080 Commented May 2, 2015 at 0:06

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

This is the simple way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.