Home > Software engineering >  PHP: any shortcut for str_starts_with and str_ends_with with haystack and needle also interverted?
PHP: any shortcut for str_starts_with and str_ends_with with haystack and needle also interverted?

Time:01-29

I need the following condition:

if (
  str_starts_with($foo, $bar) ||
  str_starts_with($bar, $foo) ||
  str_ends_with($foo, $bar) ||
  str_ends_with($bar, $foo)
) {
  ...
}

But it looks a bit eloquent, is there a shorter way to write it? Maybe with regex?

CodePudding user response:

You could try to use preg-match function

if (preg_match("/^{$foo}.*|.*{$foo}$/", $bar)
   || preg_match("/^{$bar}.*|.*{$bar}$/", $foo) ) {
    echo "A match was found...";
} 
  • Related