0

我是 php 新手并尝试使用 preg_match_all 从 url 中提取数据

问题是匹配项被转换为字符串,我无法单独提取它们

<?php
$pattern = '/<span class="product".*/i';
$string = file_get_contents('http://www.example.com/');

preg_match_all($pattern, $string, $matches);
echo '<b>preg_match_all()</b>';
echo '<pre>';
echo '<br /><b>Products:</b> ', var_dump($matches);
echo '</pre>';

退货

preg_match_all()

Products: array(1) {
  [0]=> array(7) {
      [0] => string(46) "Product 1"
      [1] => string(42) "Product 2"
      [2] => string(46) "Product 3"
      [3] => string(41) "Product 4"
      [4] => string(58) "Product 5"
      [5] => string(42) "Product 6"
      [6] => string(37) "Product 7"
  }
}

我试图一次提取一项(即单独的元素),并尽可能将每一项放入自己的变量中。示例:$product1 = "产品 1"

如果我尝试echo $matches[2];获取产品 3,则会收到未定义的偏移错误

编辑:

在此线程的帮助下:检索包含某个跨度类的数据

解决方案:

<?php
$html=file_get_contents('http://www.example.com/');
preg_match_all("/\<span class\=\"products\"\>(.*?)\<\/span\>/",$html,$b);

foreach($b as $key => $value) {
$$key = $value;
}

echo $value[4]; // Returns 4th key, or "Product 5"

是的,我在格式化代码方面很糟糕

4

1 回答 1

0
$markup = '<span class="Products-Name">Used Gibson USA</span>
    <span class="Products-Discription">Les Test Test Test Paul Custom 1986
    <br />with Factory Kahler </span>';
$markup = preg_replace('~<br\\s*/?>~si', ' ', $markup); // replace <br> with space
$markup = preg_replace('~\\s+~', ' ', $markup); // compact consecutive spaces into a single space
if(preg_match_all('~<span class="Products-(.+?)">(.*?)</span>~si', $markup, $matches)){
    // trim the enite deep array
    array_walk_recursive($matches, function(&$match){
        $match = trim($match);
    });
    // this shows you how the $matches is structured
    list($raw_matches, $class_matches, $inner_matches) = $matches;
    // combine class names with span inner value
    var_dump(array_combine($matches[1], $matches[2]));
}
// this is how you loop preg_match_all() results
foreach($matches[0] as $key => $raw_match){
    $class_match = $matches[1][$key];
    $inner_match = $matches[2][$key];
    if(!strcasecmp($class_match, 'what YOU seek')){
        echo $inner_match;
    }
}
于 2013-07-07T21:00:00.950 回答