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

问题描述 投票:3回答:2

我试图在一串/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);

但是:Kua zxsw指出

我使用https://regex101.com/r/Saxk8x/1preg_match还是有更快或更简单的方法吗?

preg_match_allpreg_match都返回null,即使Demo正常运行。

php regex string preg-match preg-match-all
2个回答
2
投票

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

stripos()

1
投票

由于$pos = strpos($str, '/target-'); if ($pos !== false) { var_dump($pos); } stripos比正则表达式更快,这里是简单的RegEx演示。

片段

strpos

检查演示$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'; }

注意:如果你只想检查一次,最好使用qazxsw poi而不是qazxsw poi。

了解更多关于here的信息

© www.soinside.com 2019 - 2024. All rights reserved.