[英]PHP: create string with values separated by comma BUT without comma at the end of string
[英]Create an UL from comma separated Values in PHP
我正在创建一个用户输入,希望他们列出链接和描述。
从头开始执行此操作,因此我愿意接受sytax建议。 我在想这样的事情:
www.ebay.com | "my Ebay" , http://www.craigslist.org?s=bla | "Craiglist" ,
www.twitter.com/ev | "My Twitter"
我想用php将其转换为UL。 我想我会为每个使用a,但是想知道实现此目标的最佳方法是什么。
所以目标:
创建类似于此的链接
<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;
应该可以带您到想要的地方。
更新请注意引号,它将破坏html。 解决方案,删除引号,如str_replace所示,或使用htmlspecialchars()将其替换为html计数器部分。
更新
在第一个位置的网址中添加了对http://的检查,如果不存在,它将被追加。 我用strpos()做一个简单的检查。
还添加了修剪并删除了周围的空格和|。 字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.