Reputation: 2988
I'm having some trouble with Converting Text to a list. The situation is that I get text like the following from the database:
"Hello, my name is michael, my hobbys are:
- computers
- guitar
and some more blabla "
No I want to transform the listed points(computers&guitar in this case) into an unordered html list, so the resulst should look like this:
"Hello, my name is michael, my hobbys are:
<ul>
<li>computers<li>
<li>guitar</li>
</ul>
and some more blabla ".
I think that the best solution would be doing this by regex, but my knowledge there isnt good enough to realise this. I tried it by replacing all /\n- /
width a <li>
tag, which worked. But how do I get the closing </li>
, and even more confusing for me, how do I get the both <ul>
tags?
Thank you in advance for any advice.
Upvotes: 0
Views: 206
Reputation: 3932
There are a bunch of ways to do this, including regex, but in your specific case the explode() function should suffice. You can do:
$array = explode("\n", $string);
Now your $array will have "Hello, my name is michael, my hobbys are:" in the first slot, "- computers" in the second, etc.
Then go over the array, and for each element that begins with "-", turn it into <li>element</li>
This is a very vanilla way of doing it, but it should be efficient and doesn't require the use of regular expressions.
Upvotes: 0
Reputation: 298206
Your syntax looks almost identical to Markdown, a simple markup language. The only difference is a little bit of whitespace:
Hello, my name is Michael, my hobbies are:
- Computers
- Guitar
and some more blabla
It's converted to this:
<p>Hello, my name is Michael, my hobbies are:</p>
<ul>
<li>Computers</li>
<li>Guitar</li>
</ul>
<p>and some more blabla</p>
There are a few PHP Markdown projects that I think you'll find useful.
Upvotes: 5