首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将标记与字符串分开?

如何将标记与字符串分开?
EN

Stack Overflow用户
提问于 2012-09-27 00:52:46
回答 5查看 103关注 0票数 0

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

我已经尝试了一个普通的函数,但输出的结果是“红,蓝,绿,暗,蓝”。我想加入“Dark”和“Blue”在同一个标签中,以及任何其他首字母为大写的单词,即使只有两个以上的单词也是如此。这有可能吗?

EN

回答 5

Stack Overflow用户

发布于 2012-09-27 00:59:40

在空格中查找explode()之后的第一个大写字母的循环应该是这样做的:

代码语言:javascript
运行
复制
$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
EN

Stack Overflow用户

发布于 2012-09-27 01:05:00

代码语言:javascript
运行
复制
$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
EN

Stack Overflow用户

发布于 2012-09-27 01:07:30

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12606654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档