duandi4815
duandi4815
2015-10-11 12:37

PHP - 有没有办法计算为您的需求而设计的正则表达式(正则表达式)?

已采纳

I'm trying to write the regex to search for image tags within a string, then to count them using either 'count' or 'substr_count'

EG: [image1], [image2] etc etc..

I'm an absolute rookie with regex so it's pretty confusing to me. Before anyone asks, yes I have done a little research into it, but I was just curious as to whether or not there is any shortcuts that are out there that myself and anyone else reading this may be missing out on.

I have also found the https://regex101.com/ however am clueless as to where to go from there.

My efforts for the example above are:

'~(\[image([\d])+\]~i'

and ..

'#[^a-z0-9.]#i'

If someone could show me how to search for the above, or point me in the right direction to a programming gold-mine it'd be more than appreciated.

Cheers, Rich

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongyan1625 dongyan1625 6年前

    Use a preg_match_all, i.e.:

    $string = <<< LOL
    some text with image1 and another
    part of that contains image2
    yet another image3
    LOL;
    
    preg_match_all('/(image\d+)/i', $string, $matches, PREG_PATTERN_ORDER);
    for ($i = 0; $i < count($matches[1]); $i++) {
        echo $matches[1][$i]."
    ";
    }
    

    OUTPUT:

    image1
    image2
    image3
    

    DEMO:

    http://ideone.com/cQymaV

    点赞 评论 复制链接分享
  • duanjue7508 duanjue7508 6年前

    The preg_match_all function already returns the number of occurrences, you don't need to use count or something else:

    if (false !== $count = preg_match_all('~\[image\d+]~i', $text))
        echo $count;
    
    点赞 评论 复制链接分享