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

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

<分区>

我试图在 /dir1/dir2/dir3/dir4/../dir7/dir8/dir9/target- 的字符串中查看 /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 还是有更快或更简单的方法?

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

最佳答案

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

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

关于php - 正则表达式检查另一个字符串中是否存在一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116858/

相关文章:

java - : I have a requirement of matching the value request parameter with unicode charcters but it should not allow space 的正则表达式

用于验证前 n 个字符的正则表达式

linux - Swift 字符串 hasSuffix 错误

php - 使用附加列将 PHP 数组放入 MySQL

php - 调用多个 CSS 文件

javascript - AngularJS 在列中使用 ng-repeat 填充表格

PHP 网页抓取

不使用 setString 的 Java SQL 转义

c++ - 字节缓冲区到字符串

php - 来自 PHP 的 ID 未传递到 URL