0

我想将这样的字符串拆分成另一个用逗号分隔的字符串,就像这样的“红色,蓝色,绿色,深蓝色”。

我已经尝试了一个正常的功能,但这会输出“红、蓝、绿、暗、蓝”。我想在同一个标​​签中加入“Dark”和“Blue”以及任何其他首字母大写的单词,即使只有两个以上的单词。那可能吗?

4

5 回答 5

0

我的建议是有一本颜色字典,比如小写。然后在字典中的单词之后搜索传入的字符串。如果命中将该颜色添加到输出字符串并添加逗号字符。您需要从输入字符串中删除找到的颜色。

于 2012-09-26T17:07:30.203 回答
0
$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-26T17:04:59.640 回答
0

这是我的建议.. 仅在需要时才使用逗号

$var = "roto One Two Three Four koko poko Toeo Towe ";

$var = explode(' ', $var);

$count = count($var);
for($i=0; $i<$count; $i++)  
    if( (ord($var[$i][0]) > 64 and  ord($var[$i+1][0]) > 96) or ord($var[$i][0]) > 96) 
            $var[$i] .=',';

echo $var = implode(' ',$var);  
于 2012-09-26T17:36:26.393 回答
0

你可以试试

    $colors = "red blue green Dark Blue Light green Dark red";
$descriptors = array("dark","light");

$colors = explode(" ", strtolower($colors));
$newColors = array();
$name = "";
foreach ( $colors as $color ) {
    if (in_array(strtolower($color), $descriptors)) {
        $name = ucfirst($color) . " ";
        continue;
    } else {
        $name .= ucfirst($color);
        $newColors[] = $name;
        $name = "";
    }
}
var_dump($newColors);
var_dump(implode(",", $newColors));

输出

array
  0 => string 'Red' (length=3)
  1 => string 'Blue' (length=4)
  2 => string 'Green' (length=5)
  3 => string 'Dark Blue' (length=9)
  4 => string 'Light Green' (length=11)
  5 => string 'Dark Red' (length=8)

string 'Red,Blue,Green,Dark Blue,Light Green,Dark Red' (length=45)
于 2012-09-26T17:09:48.417 回答
0

在空间上寻找第一个大写字母的循环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-26T16:59:40.297 回答