HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Wrapping text in <a> tags

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
textwrappingtags

Problem

I needed a script to wrap phrases with tag, they all are separated by commas, for i.e "Alan, Bob, John".

I came to this result:

$actors = explode(',', $item->casting);

        $item->casting = array_map(function($a) {
            $a = trim($a);
            return ''.$a.'';
        }, $actors);

        echo implode(' ', $item->casting);


I'd like to know is there a better way achieve this result ?

Solution

Your code doesn't handle names with spaces within, nor names with characters that are illegal for URL's. To accomodate these two issues, you could use something like:

$item->casting = 'André, Ann Charlotte, Bob, Kåre Ronny';

$actors = array();

foreach (explode(',', $item->casting) as $actor) {
    $actor = trim($actor);
    $actors[] = ''. $actor .'';
}

echo implode(', \n', $actors);


Which would produce the following output:

André, 
Ann Charlotte, 
Bob, 
Kåre Ronny


I kind of prefer building the $actors array, as that allows me easily to change output variants. But you could also opt for using echo directly, which would eliminate the need for the entire $actors table. I did however removing the original $actors and included that directly in the foreach, as I try to keep intermediary variables to a minimum.

PS! Depending on font settings and encoding elsewhere, you could consider calling htmlspecialchars() in addition before using in the URL.

Code Snippets

$item->casting = 'André, Ann Charlotte, Bob, Kåre Ronny';

$actors = array();

foreach (explode(',', $item->casting) as $actor) {
    $actor = trim($actor);
    $actors[] = '<a href="'. urlencode($actor) .'">'. $actor .'</a>';
}

echo implode(', \n', $actors);
<a href="Andr%C3%A9">André</a>, 
<a href="Ann+Charlotte">Ann Charlotte</a>, 
<a href="Bob">Bob</a>, 
<a href="K%C3%A5re+Ronny">Kåre Ronny</a>

Context

StackExchange Code Review Q#112038, answer score: 2

Revisions (0)

No revisions yet.