多使用sprintf和printf吧。Forget Concatenation; Format your strings!

在php中,字符串连接操作太常用了。
在javascript中也是如此。前几天写了一篇文章专门讲javascript中字符串连接效率的,有兴趣可以看一下:
javascript中的高性能字符串连接操作》。

在php中,如果要连接几个变量或者常量,.是最好用的了。
比如:

$money = 29.5;

print "Approximately ".intval($money).".";

但是这种操作有二个缺点:
1 any sort of string formatting must be done manually。
上例中, 用到了intval()来format $money这个变量。
2 it is difficult to visualize the “goal” string when it is sufficiently complex。

所以使用sprintf和printf吧。

看下面的代码:

<?php

$money = 29.5;

printf('Approximately $%d.', $money);

// outputs: Approximately $29.

// 是不是很方便。

 

printf('Exactly $%01.2f.', $money);

// outputs: Exactly $29.50.

 

$total = 1;

printf("%d item%s total.", $total, $total != 1 ? 's' : '');

// outputs: 1 item total.

$total++;

printf("%d item%s total.", $total, $total != 1 ? 's' : '');

// outputs: 2 items total.
<?php

$email = '[email protected]';

 

printf('<a href="mailto:%1$s">%1$s</a>', htmlentities($email));

echo '<a href="mailto:' . htmlentities($email) . '>' 

    . htmlentities($email) . '</a>';

明显使用printf的时候,代码的可读性更高。

再来看一个sql语句的例子:

<?php

$userId = 1;

$limit  = 10;

$offset = 30;

 

$columns = array(

    'b.id', 'b.title', 'b.date', 'b.content', 'u.name', 'u.email'

);

 

$where = array(

    $dbAdapter->quoteInto('u.id = ?', $userId),

    'b.date_published is not null'

);

 

$dbAdapter->query(sprintf(

    'SELECT %s 

        FROM Blog b INNER JOIN User u ON u.id = b.user_id 

        WHERE %s LIMIT %d OFFSET %d',

    implode(', ', $columns), implode(' AND ', $where), $limit, $offset

));

 

$dbAdapter->query(

    'SELECT ' . implode(', ', $columns) 

        . ' FROM Blog b INNER JOIN User u ON u.id = b.user_id 

            WHERE ' . implode(' AND ', $where) 

        . ' LIMIT ' . (int)$limit . ' OFFSET ' . (int)$offset

);

确实很不错。

不过,如果要连接数十个变量,那么sprintf的参数列表岂不是要太长了?
那么就用vsprintf 吧。

print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01

简直太优美了。

既然说到格式化字符串,那就再多说几句:

如果要格式化一些金额方面的数字,可以使用number_format()或者money_format()。
这二个函数务必记在心里,即使不会用,也要记得函数名。
记得某电子商务公司笔试题里面有这个。

<?php

$money  = "1234567";

print number_format($money);

 

//1,234,567

你可能感兴趣的:(String)