如何从字符串中分离标签?

时间:2012-09-26 16:52:46

标签: php tags

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

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分:0)

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

答案 3 :(得分: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)

答案 4 :(得分: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);  
相关问题