2012-09-26 17 views
0

我想將這樣的「紅藍綠深藍」字符串分隔成另一個字符,用逗號分隔,就像這個「紅藍綠深藍」。我如何從字符串中分離標籤?

我已經試過了一個正常的功能,但是輸出「紅色,藍色,綠色,黑色,藍色」。我想在同一個標​​籤和任何第一個字母大寫的單詞中加入「黑色」和「藍色」,即使只有兩個單詞也是如此。那可能嗎?

+0

是隻有當一個逗號,但你需要有一個字典在顏色的名字。如果不是的話,你需要有一種策略,所有的顏色都是從versals開始的。否則,你知道......一個空間是一個空間是一個空間...... – opaque

回答

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 
+0

那麼,如果你可以指望他們是第一個字符的經文... – opaque

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); 
0

我的建議是有顏色的字典,在說小寫。 然後搜索字典中的單詞之後的傳入字符串。如果命中將該顏色添加到輸出字符串並添加逗號字符。您需要從輸入字符串中移除找到的顏色。

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) 
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); 
相關問題