简体   繁体   English

从PHP中的逗号分隔值创建UL

[英]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. 从头开始执行此操作,因此我愿意接受sytax建议。 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. 我想用php将其转换为UL。 I think I would use a for each but wanted to see what the best way to go about this would be. 我想我会为每个使用a,但是想知道实现此目标的最佳方法是什么。

so goals: 所以目标:

  1. Grab URL, if HTTP is append it, take it off 抓取URL,如果将HTTP附加在URL后面,则将其删除
  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. 更新请注意引号,它将破坏html。 Solution, remove the quotes as shown with str_replace or replace them with their html counter part using htmlspecialchars() . 解决方案,删除引号,如str_replace所示,或使用htmlspecialchars()将其替换为html计数器部分。

Update 更新

Added a check for http:// in the url at the first position, if it is not there it will be appended. 在第一个位置的网址中添加了对http://的检查,如果不存在,它将被追加。 I used strpos() to do a simple check. 我用strpos()做一个简单的检查。

Also added trim and removed the spaces around , and the | 还添加了修剪并删除了周围的空格和|。 characters. 字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM