About regular expression

Hello,

I want it to remove slashes at the beginning and end of the directory path. Is this regular expression correct?

$string = "/dir/dir/dir/dir/";
or
$string = "//dir/dir/dir/dir/";
or
$string = "/dir/dir/dir/dir//";
or
$string = "dir/dir/dir/dir/";
or
$string = "/dir/dir/dir/dir";

preg_replace(['/^\/\//','/^\//','/\/*$/'], '', $string);

I want the following output
Output: dir/dir/dir/dir
$inputs = [
    "/dir/dir/dir/dir/",
    "//dir/dir/dir/dir/",
    "/dir/dir/dir/dir//",
    "dir/dir/dir/dir/",
    "/dir/dir/dir/dir"
];

foreach ($inputs as $string) {
    echo preg_replace('/^\/+|\/+$/', '', $string) . "\n";
}

this will output dir/dir/dir/dir , as desired.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service