开发者

Remove first comma from on-the-fly string

开发者 https://www.devze.com 2023-03-26 01:06 出处:网络
As I\'m a bit of php noob, I\'m not sure whether to go with preg_replace() or to explode() then implod开发者_开发百科e().Either way, I don\'t know how to go about it.

As I'm a bit of php noob, I'm not sure whether to go with preg_replace() or to explode() then implod开发者_开发百科e(). Either way, I don't know how to go about it.

I'm in wordpress, and I'm running this code:

<?php $terms = wp_get_post_terms($post->ID,'jobtype');
foreach($terms as $term){echo ', ' . $term->name;} ?>

I need to capture into a string the echo ', ' . $term->name; and remove that first ', '.

Even if there's a different way I can echo the term names, could you guys (and gals) help me out?

Thanks!


Old school:

$terms = wp_get_post_terms($post->ID,'jobtype');
$names = array();
foreach($terms as $term){
    $names[] = $term->name;
}
echo implode(',', $names);

As PHP 5.3 introduced anonymous functions [docs], array_map [docs] becomes more interesting for these "one time" jobs:

echo implode(',', array_map(function($term) { return $term->name; }, 
                            wp_get_post_terms($post->ID,'jobtype')));

Or maybe more descriptive with a reusable function:

function getProperty($prop) {
    return function($object) use ($prop) {
        return $object->{$prop};
    }
}

echo implode(',', array_map(getProperty('name'), 
                            wp_get_post_terms($post->ID,'jobtype')));

But as said, this only works if you use PHP 5.3.

0

精彩评论

暂无评论...
验证码 换一张
取 消