dsirr48088
dsirr48088
2013-03-28 18:00

如何从php中的字符串中获取冒号分隔值

已采纳

I have a string

$style = "font-color:#000;font-weight:bold;background-color:#fff";

I need only

font-color
font-weight
background-color

I have tried

preg_match_all('/(?<names>[a-z\-]+:)/', $style, $matches);

var_dump($matches);

it gives me following output

array
  0 => 
    array
      0 => string 'font-color:' (length=11)
      1 => string 'font-weight:' (length=12)
      2 => string 'background-color:' (length=17)
  'names' => 
    array
      0 => string 'font-color:' (length=11)
      1 => string 'font-weight:' (length=12)
      2 => string 'background-color:' (length=17)
  1 => 
    array
      0 => string 'font-color:' (length=11)
      1 => string 'font-weight:' (length=12)
      2 => string 'background-color:' (length=17)

There are three problems with this output 1. It is two or three dimensional array, I need one dimensional array. 2. It is repeating the information 3. It is appending ":" at the end of each element.

I need a single array like this

array
0 => 'font-color'
1 => 'font-weight'
2 => 'background-color'
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dqz86173 dqz86173 8年前

    Take out the colon:

    $style = "font-color:#000;font-weight:bold;background-color:#fff";
    preg_match_all('/(?<names>[a-z\-]+):/', $style, $matches);
    
    var_dump($matches['names']);
    

    Then use $matches['names'], since you named it, so you dont have redundant informations

    点赞 评论 复制链接分享

相关推荐