【发布时间】:2011-12-27 23:07:09
【问题描述】:
我在数据库表中有一个字符串,用逗号分隔,即 this,is,the,first,sting
我想做但不知道如何将字符串输出如下: this, is, the, first and string
注意空格,最后一个逗号被“and”代替。
【问题讨论】:
我在数据库表中有一个字符串,用逗号分隔,即 this,is,the,first,sting
我想做但不知道如何将字符串输出如下: this, is, the, first and string
注意空格,最后一个逗号被“and”代替。
【问题讨论】:
这可能是您的解决方案:
$str = 'this,is,the,first,string';
$str = str_replace(',', ', ', $str);
echo preg_replace('/(.*),/', '$1 and', $str);
【讨论】:
第一次使用,本回答提供的功能:PHP Replace last occurrence of a String in a String?
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos === false)
{
return $subject;
}
else
{
return substr_replace($subject, $replace, $pos, strlen($search));
}
}
然后,您应该对文本执行一个通用的 str_replace 来替换所有其他逗号:
$string = str_lreplace(',', 'and ', $string);
str_replace(',',', ',$string);
【讨论】:
$words = explode( ',', $string );
$output_string = '';
for( $x = 0; $x < count($words); x++ ){
if( $x == 0 ){
$output = $words[$x];
}else if( $x == (count($words) - 1) ){
$output .= ', and ' . $words[$x];
}else{
$output .= ', ' . $words[$x];
}
}
【讨论】: