我有一个像这样的充满地址的sql表
Hattie:07903 000066::Dad:07854 000095::Tom:07903 000044::Allistair:07765 000005::Home:0115 974 0000::
我想拆分每个联系人,以便每个联系人的姓名和号码都回显到列表框中的单独面板中,如下所示
<ol>
<li>Hattie:07903 000066</li>
<li>Dad:07854 000095</li>
</ol>
任何帮助都会很棒。
谢谢
最佳答案
在 Perl 中毫不费力:
#! /usr/bin/perl
local $_ = "Hattie:07903 000066::Dad:07854 000095::Tom:07903 000044::Allistair:07765 000005::Home:0115 974 0000::";
print "<ol>\n",
map("<li>$_</li>\n", split /::/),
"</ol>\n";
如您的问题所用,序列 ::
是一个终止符 而不是分隔符,这使得 split
有点概念不匹配。为了更符合格式,请在列表上下文中使用正则表达式匹配 /g
The
/g
modifier specifies global pattern matching—that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression.
和一个非贪婪量词
By default, a quantified subpattern is “greedy,” that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a
?
. Note that the meanings don't change, just the “greediness” …
相当于
print "<ol>\n",
map("<li>$_</li>\n", /(.+?)::/g),
"</ol>\n";
无论哪种方式,输出都是
<ol> <li>Hattie:07903 000066</li> <li>Dad:07854 000095</li> <li>Tom:07903 000044</li> <li>Allistair:07765 000005</li> <li>Home:0115 974 0000</li> </ol>
关于php - 拆分并回显到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541215/