正则表达式匹配插入符号和破折号

时间:2015-03-10 02:34:53

标签: php regex preg-replace preg-match

尝试匹配^grape-ape之类的字符串,以使用Leafly API运行搜索。我只是不擅长正则表达,我的阅读障碍使我失去了模式。

任何想法为什么它似乎不匹配/替换?

/*********************/
/* Tag Search Test           */
/*********************/
$str = 'I really love that ^blue-dream and ^grape-ape';

preg_match('/^\^([a-z0-9\-])/i', $str, $match);

if (!(empty($match)) && $match != false) {
    $slugs = $match;
    if(!(is_array($slugs))) {
        $strain = exec('curl -v -H "app_id:*******************" -H "app_key:*******************" -X GET "http://data.leafly.com/strains/'.$slugs.'"');
        if (is_array(json_decode($strain))) {
            $str = preg_replace('/^\^('.preg_quote($slugs).')/i', '<span title="'.$strain['descriptionPlain'].'">'.$strain['name'].'</span>', $str);
        }
    } else {
        foreach($slugs as $slug) {
            $strain = exec('curl -v -H "app_id:*******************" -H "app_key:*******************" -X GET "http://data.leafly.com/strains/'.$slug.'"');
            if (is_array(json_decode($strain))) {
                $str = preg_replace('/^\^('.preg_quote($slug).')/i', '<span title="'.$strain['descriptionPlain'].'">'.$strain['name'].'</span>', $str);
            }
        }
    }
}

echo '<pre>';
print_r($str);
echo '</pre>';


/*********************/
/* Reference Test             */
/*********************/
$strain = exec('curl -v -H "app_id:*******************" -H "app_key:*******************" -X GET "http://data.leafly.com/strains/grape-ape"');

echo '<pre>';
print_r(json_decode($strain));
echo '</pre>';

1 个答案:

答案 0 :(得分:0)

由于上一张海报出于某种原因删除了他们的答案,而我试图使代码正常工作,我想我会发布答案。

我的问题实际上是在验证API请求,preg_match()的实现应该是preg_match_all()

/*********************/
/* Tag Search Test           */
/*********************/
$str = 'I really love that ^blue-dream and ^grape-ape';

preg_match_all('/\^([a-z0-9\-]+)/i', $str, $match);

$i = 0;
foreach ( $match[1] as $slug ) {
    $strain = (array) json_decode(exec("curl -v -H 'app_id:16d45ca2' -H 'app_key:9c699ac21615ef7a159cab290c1a6f2f' -X GET 'http://data.leafly.com/strains/$slug'"));
    $str = str_replace($match[0][$i], '<span title="'.$strain['descriptionPlain'].'">'.$strain['name'].'</span>', $str);
    $i++;   
}