Regex to check the existence of a string in another string

Viewed 585

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.

2 Answers

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);
}

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

Related