【问题标题】:Regex to check the existence of a string in another string [duplicate]正则表达式检查另一个字符串中是否存在字符串[重复]
【发布时间】:2023-03-04 16:42:02
【问题描述】:

我试图在/dir1/dir2/dir3/dir4/../dir7/dir8/dir9/target-.a-word1-word2-alphanumberic1-alphanumberic2.md 的字符串中查看/target- 的存在。

$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_matchpreg_match_all 还是有更快或更简单的方法?

即使 Demo 功能正常,preg_matchpreg_match_all 都返回 null。

【问题讨论】:

  • 你试过stripos()吗?
  • 听起来这个问题更适合代码审查。
  • 您在正则表达式中使用捕获组,就好像您需要捕获路径、目标和文件名一样。那是对的吗? target 是静态的还是 Target 和其他变体?

标签: php regex string preg-match preg-match-all


【解决方案1】:

由于striposstrpos 比正则表达式更快,这里是简单的正则表达式演示。

片段

$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

【讨论】:

    【解决方案2】:

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

    $pos = strpos($str, '/target-');
    if ($pos !== false) {
        var_dump($pos);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2018-05-24
      • 2012-02-17
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      相关资源
      最近更新 更多