代码之家  ›  专栏  ›  技术社区  ›  Emma

如何编写一个regex来检查另一个字符串中间的字符串?

  •  2
  • Emma  · 技术社区  · 6 年前

    我想看看 /target- 一串 /dir1/dir2/dir3/dir4/../dir7/dir8/dir9/target-.a-word1-word2-alphanumberic1-alphanumberic2.md )

    $re = '/^(.*?)(\/target-)(.*?)(\.md)$/i';
    $str = '/dir1/dir2/dir3/dir4/../dir7/dir8/dir9/target-.a-word1-word2-alphanumberic1-alphanumberic2.md';
    
    preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);
    
    // Print the entire match result
    var_dump($matches);
    

    演示: https://regex101.com/r/Saxk8x/1

    我是否使用 preg_match preg_match_all 还是有更快或更容易的方法?

    两个 预匹配 普雷格尔马奇亚尔 即使demo运行正常,也返回空值。缺少什么?

    非常感谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   RadicalDingos    6 年前

    如果你只需要找到确切的字符串 /target- ,你可以使用 strpos() ( stripos() 如果需要不区分大小写的搜索)。它将比最好的正则表达式更快。

    $pos = strpos($str, '/target-');
    if ($pos !== false) {
        var_dump($pos);
    }
    
        2
  •  1
  •   Shahnawaz Kadari    6 年前

    自从 stripos strpos 比正则表达式快,这里是简单的regex演示。

    片断

    $re = '/\/target\-/';
    $str = '/dir1/dir2/dir3/dir4/../dir7/dir8/dir9/target-.a-word1-word2-alphanumberic1-alphanumberic2.md';
    
    if(preg_match($re, $str, $match)){
    echo $match[0].' found';
    }else{
    echo 'Aww.. No match found';
    }
    

    检查演示 here

    注意:如果你只想检查一次,最好使用 preg_match 而不是 preg_match_all .

    阅读更多有关 preg_match