dongwei3336
dongwei3336
2015-03-10 02:34

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

已采纳

Trying to match a string like ^grape-ape to run a search using Leafly API. I am just no good at regex, my dyslexia looses me on the patterns.

Any ideas why it doesn't seem to be matching/replacing?

/*********************/
/* 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条回答

  • duan33360 duan33360 6年前

    Since the last poster removed their answer for some reason while I attempted to get the code to work properly I guess I'll post the answer.

    My problem was actually in the verification of the API request, and the implementation of the preg_match() which should be 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++;   
    }
    
    点赞 评论 复制链接分享

相关推荐