2012-10-12 21 views
0

我期待抢位于看起来像这样的字符串的数据: string(22) "width="16" height="16""爆炸,在有引号的字符串它

我希望能使用爆炸功能抢到16个和16个值并将它们放入我可以使用的数组中。但我不知道如何在PHP中使用explode函数中的$num。通常我只有一个可以使用的逗号。

事情是这样的,但我知道这是错误的:

$size = "width="16" height="16"" 
$sizes = explode('""', $size); 

这一切确实是:array(1) { [0]=> string(5) "Array" }

回答

1

试试这个

preg_match_all('/"([^"]+)"/', 'width="16" height="16"', $matches); 
$result = $matches[1]; 

/* print_r($result); 
Array 
(
     [0] => 16 
     [1] => 16 
) 
*/ 
+0

我认为这是最好的 – estern

0

你可以使用正则表达式来选择值,如果他们将是唯一的数字在字符串(1234567890)中。 preg_filter()会做这样的事情 - 只要让你的“替换”替换自己的比赛('$1')。

2

奇怪的变量。

无论哪种方式,为什么不使用拆分命令?

$size = 'width="16" height="16"'; 

$split_sizes = explode('"',$size); 
$count = count($split_sizes); 

for ($i = 1; $i < $count; $i += 2) { 
    $sizes[] = $split_sizes[$i]; 
} 

这里的假设是字符串将只填充成对的未加引号的键和双引号值。

+0

完美,正是我一直在寻找! – estern

3

explode()不会为你做这个;它只是将一个字符串分割成一个常量分隔符(比如逗号),而你需要做的是从引号之间提取文本。在这个简单的例子,你可以使用preg_match_all()来完成这项工作:

$str = 'width="16" height="16"'; 
preg_match_all('/\"(.*?)\"/', $str, $matches); 
print_r($matches); 

回报

Array 
(
    [0] => Array 
    (
     [0] => "16" 
     [1] => "16" 
    ) 

    [1] => Array 
    (
     [0] => 16 
     [1] => 16 
    ) 
) 

- 换句话说,在preg_match_all()调用之后,$匹配[1]包含一个由该模式匹配的值数组,在这种情况下,它是您所追踪的属性值。

+0

+1,因为不使用爆破旧式的方式。不知道为什么你在那里有问号,因为已经有一个星号。也许它应该在括号之外? – johnrom

+0

感谢您的回答,这看起来像一个干净的方式,使用较少的代码。 – estern

+0

@johnrom:问号将*量词变成吝啬;默认情况下它会匹配尽可能多的字符,在这种情况下,它会使它匹配'16“height =”16“ - 字符串中第一个引号和最后一个之间的所有内容。如果这不是您以前遇到过的情况,您可能希望提高对Perl兼容正则表达式的熟悉程度。 –

1

这是我会怎么做:

$size = 'width="16" height="16" maxlength="200"'; 
preg_match_all('/([A-Za-z\-]+)=/',$size,$fields); 
preg_match_all('/[A-Za-z\-]+="([A-Za-z0-9_\-]+)"/',$size,$values); 
var_dump($fields[1]); 
var_dump($values[1]); 

// gives you 
array(3) { 
    [0]=> 
    string(5) "width" 
    [1]=> 
    string(6) "height" 
    [2]=> 
    string(9) "maxlength" 
} 
array(3) { 
    [0]=> 
    string(2) "16" 
    [1]=> 
    string(2) "16" 
    [2]=> 
    string(3) "200" 
} 
0

如何摆脱双引号和爆炸的空间。然后,$尺寸将如下所示:

{ 
    [0]=> width=16 
    [1]=> height=16 
} 

然后,您可以在等号上分解$尺寸的每个切片以获取值。

{ 
    [0] => width 
    [1] => 16 
} 
{ 
    [0] => height 
    [1] => 16 
} 

示例代码:

<?php 

$size = 'width="16" height="16"; 
//get rid of all double quotes 
$size = str_replace('"', '', $size); 
$sizes = explode(' ', $size); 
//show what is in the sizes array 
print_r($sizes); 
//loop through each slide of the sizes array 
foreach($sizes as $val) 
{ 
    $vals = explode('=', $val); 
//show what is in the vals array during this iteration 
    print_r($vals); 
} 

?> 
0

您可以简单地使用

explode("\"",$string);