简体   繁体   中英

Create an UL from comma separated Values in PHP

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:

  1. Grab URL, if HTTP is append it, take it off
  2. Grab Description
  3. Create link, similar to this

     <a href="http://<?php echo $link; ?>"><?php echo $desc; ?></a></li> 
$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.

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