Split and echo into a list
i have a sql table full of address' like this
Hattie:07903 000066::Dad:07854 000095::Tom:07903 000044::Allistair:07765 000005::Home:0115 974 0000::
i would like to split each and every one so that th开发者_开发问答e name and number of each contact is echoed into a seprate panel within a listbox like below
<ol>
<li>Hattie:07903 000066</li>
<li>Dad:07854 000095</li>
</ol>
Any help would be brilliant.
Thanks
SEO Leicester
No sweat in 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";
As used in your question, the sequence ::
is a terminator and not a separator, which makes split
a bit of a conceptual mismatch. To fit the format more closely, use a regular-expression match in list context with /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.
and a non-greedy quantifier
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” …
That amounts to
print "<ol>\n",
map("<li>$_</li>\n", /(.+?)::/g),
"</ol>\n";
Either way, the output is
<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>
You can split your string like this:
$adresses = explode("::", $yourString)
And then a simple foreach will print the content as you wish.
It would be better to restructure your database so that addresses aren't stored as a delimited string, but with each address as a row in an addresses table... preferably with the name and address as separate columns... makes it a lot harder for searching, and for manipulation of the data (adding a new address, etc)
$addresses = explode('::',$addressField);
echo '<ol>';
foreach($addresses as $address) {
echo '<li>',$address,'</li>';
}
echo '</ol>';
EDIT
(Shamelessly stealing formatting from Prix's answer)
$addresses = explode('::',$addressField);
echo '<ol>';
foreach($addresses as $address) {
list($name,$phone) = explode(':',$address);
echo '<li>Name: ',$name,' Telephone: ',$phone,'</li>';
}
echo '</ol>';
精彩评论