我想把像“红蓝绿深蓝”这样的字符串分割成用逗号分隔的字符串,就像“红,蓝,绿,深蓝”一样。
我已经尝试了一个普通的函数,但输出的结果是“红,蓝,绿,暗,蓝”。我想加入“Dark”和“Blue”在同一个标签中,以及任何其他首字母为大写的单词,即使只有两个以上的单词也是如此。这有可能吗?
发布于 2012-09-27 00:59:40
在空格中查找explode()
之后的第一个大写字母的循环应该是这样做的:
$string = "red blue Dark Green green Dark Blue";
// preg_split() on one or more whitespace chars
$words = preg_split('/\s+/', $string);
$upwords = "";
// Temporary array to hold output...
$words_out = array();
foreach ($words as $word) {
// preg_match() ins't the only way to check the first character
if (!preg_match('/^[A-Z]/', $word)) {
// If you already have a string built up, add it to the output array
if (!empty($upwords)) {
// Trim off trailing whitespace...
$words_out[] = trim($upwords);
// Reset the string for later use
$upwords = "";
}
// Add lowercase words to the output array
$words_out[] = $word;
}
else {
// Build a string of upper-cased words
// this continues until a lower cased word is found.
$upwords .= $word . " ";
}
}
// At the end of the loop, append $upwords if nonempty, since our loop logic doesn't
// really account for this.
if (!empty($upwords)) {
$words_out[] = trim($upwords);
}
// And make the whole thing a string again
$output = implode(", ", $words_out);
echo $output;
// red, blue, Dark Green, green, Dark Blue
发布于 2012-09-27 01:05:00
$words = explode(' ',$string);
$tags = '';
$tag = '';
foreach($words as $word)
{
if(ord($word >=65 and ord($word <=65))
{
$tag .= $word.' ';
}
else
$tags .= $word.',';
}
$tags = trim($tags,',').trim($tag);
print_r($tags);
发布于 2012-09-27 01:07:30
我的建议是有一本颜色字典,比如小写的。然后在字典中的单词后面搜索传入的字符串。如果命中,则将颜色添加到输出字符串并添加逗号字符。您需要从输入字符串中删除找到的颜色。
https://stackoverflow.com/questions/12606654
复制相似问题