PHP explode string, concat with search url and echo it
I have names of actors in variable $actor
Example:
Actor One, Actor Two,Someone
I 开发者_C百科need to split the string per person. I figured I'd use explode to get something like this:
[0] => Actor One
[1] => Actor Two
[2] => Someone
Then I need to build search links in following format:
http://site.com/?s=Actor+One
http://site.com/?s=Actor+Two
http://site.com/?s=Someone
And finally echo it like this:
<a href='http://site.com/?s=Actor+One'>Actor One</a>, <a href='http://site.com/?s=Actor+Two'>Actor Two</a>, <a href='http://site.com/?s=Someone'>Someone</a>
I'm just totally lost in PHP syntax. Help is appreciated.
(this is homework, isn't it?)
Anyway:
// $actors is an array with the names
$actors = explode(',', $actor);
foreach ($actors as $name) {
$e_name = urlencode($name);
print "<a href=\"http://site.com/?s={$e_name}\">" . htmlentities($name) . "</a>";
}
<?php
$arr = array('Actor One','Actor Two','Someone');
foreach($arr as $value){
echo '<a href="http://site.com/?s='.rawurlencode($value).'">'.htmlentities($value).'</a>';
}
?>
Oops url encoding.. my bad!
Just to post a safe version that works independently of whether the array content has been maliciously prepared:
$cs = "UTF-8";
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", $cs);
/* ... */
foreach($actor as $name)
{
print('<a href="http://site.com/?s=' . htmlentities(urlencode($name), ENT_QUOTES, $cs)
. '">' . htmlentities($name, ENT_QUOTES, $cs) . '</a>');
Probably best to include the encoding as well, after all your array could contain all sorts of characters.
There are lots of steps to what you need to do:
explode
the string into an array (as you did)- Create and echo the links with those urls
- When the actor name goes into a url, remember to
rawurlencode
it - When it goes into HTML, remember to
htmlspecialchars
it
So the above can be translated into this code:
$actors = explode(',', $actor);
foreach($actors as $actor) {
printf('<a href=\'http://site.com/?s=%s\'>%s</a>',
rawurlencode($actor),
htmlspecialchars($actor));
}
精彩评论