爆炸出一个带引号的字符串

时间:2012-10-12 18:17:40

标签: php arrays quotes explode

我希望获取位于字符串中的数据,如下所示: string(22) "width="16" height="16""

我希望使用explode函数来获取16和16值并将它们放入我可以使用的数组中。但我不知道如何在PHP的explode函数中定位$num。通常我只有一个逗号,我可以使用。

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

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

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

7 个答案:

答案 0 :(得分:4)

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()调用之后,$ matches [1]包含一个与模式匹配的值数组,在这种情况下是你所追求的属性值。

答案 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];
}

这里的假设是字符串只会填充一对不带引号的键和双引号值。

答案 2 :(得分:1)

试试这个

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

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

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

如何摆脱双引号并在空间上爆炸。那么$ sizes将如下所示:

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

然后,您可以在等号上展开每个$ size的切片以获取值。

{
    [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);
}

?>

答案 6 :(得分:0)

您只需使用

即可
explode("\"",$string);
相关问题