dongwei3336 2015-03-10 02:34
浏览 124
已采纳

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

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 2015-03-10 17:06
    关注

    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++;   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧