Reputation: 26317
I'm creating a user input where I want them to list links as well as descriptions.
Doing this from scratch, so I'm open to sytax suggestions. I was thinking of something like this:
www.ebay.com | "my Ebay" , http://www.craigslist.org?s=bla | "Craiglist" ,
www.twitter.com/ev | "My Twitter"
I'd like to convert this into an UL with php. I think I would use a for each but wanted to see what the best way to go about this would be.
so goals:
Create link, similar to this
<a href="http://<?php echo $link; ?>"><?php echo $desc; ?></a></li>
Upvotes: 1
Views: 261
Reputation: 18853
$data = explode(",", $string);
$list = "<ul>";
foreach ($data as $item) {
list($website, $title) = explode("|", $item);
// Clean up the extra white spaces, if any.
$website = trim($website);
$title = trim($title);
// make lowercase for the below check
$website = strtolower($website);
// if website does not have http:// append it
$website = (strpos($website, "http://") !== 0)?"http://" . $website:$website;
$title = str_replace('"', "", $title); // optional, but incase you do not want the quotes.
//If you do want them, then I would suggest htmlspecialchars so it does not mess up the title attribute below.
$list .= '<li><a href="' . $website . '" title="' . $title . '">' . $title . '</a></li>';
}
$list .= '</ul>';
echo $list;
Should get you to where you want to be.
Update Note the quote remark, it will break the html. Solution, remove the quotes as shown with str_replace or replace them with their html counter part using htmlspecialchars().
Update
Added a check for http:// in the url at the first position, if it is not there it will be appended. I used strpos() to do a simple check.
Also added trim and removed the spaces around , and the | characters.
Upvotes: 3