3

I'm trying to see the existence of /target- in a string of /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);

Demo: https://regex101.com/r/Saxk8x/1

Do I use preg_match or preg_match_all or are there faster or easier ways to do so?

Both preg_match or preg_match_all return null, even though Demo functions properly.

Emma
  • 27,428
  • 11
  • 44
  • 69
  • 3
    Have you tried just with [`stripos()`](http://php.net/manual/en/function.stripos.php)? – Dharman Jan 09 '19 at 19:20
  • 1
    Sounds like this question is better suited on code review. – Andreas Jan 09 '19 at 19:31
  • 1
    You use capture groups in the regex as if you need to capture the path, target and file name. Is that correct? Is `target` static or can it be `Target` and other variations also? – Andreas Jan 09 '19 at 20:28

2 Answers2

1

If you just need to find the exact string /target-, you can use strpos() (stripos() if you want a case-insensitive search). It will be faster than the best regex.

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

Since stripos and strpos is faster than regular expression, Here is simple working RegEx demo.

Snippet

$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';
}

Check demo here

Note: If you want check only one occurance it's better to use preg_match rather than preg_match_all .

Read more about preg_match

Shahnawaz Kadari
  • 1,423
  • 1
  • 12
  • 20