正则表达式检查另一个字符串中是否存在一个字符串

Regex to check the existence of a string in another string

我试图在 /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_match 还是 preg_match_all 还是有更快或更简单的方法?

两者 preg_matchpreg_match_all return 均无效,即使演示功能正常。

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

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

由于 striposstrpos 比正则表达式快,这里是简单的 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