Replace any line before "/", PHP

I want to replace any line before "/", regardless of the length of the line.

Thanks jean

+3
source share
3 answers

in one case, if you want to change the line before the first "/".

$str = "anystring/the_rest/blah";
$s = explode("/",$str);
$s[0]="new string";
print_r ( implode("/",$s) );
+7
source
echo preg_replace('/^[^\/]+/', 'baz', 'foo/bar');
+4
source

Something like this would be most efficient, although I still prefer the preg_replace () method

$pos = strpos($input, '/');
if ($pos >= 0) {
    $output = $replacement . substr($input, $pos);
} else {
    $output = $input;
}
0
source

Source: https://habr.com/ru/post/1733149/


All Articles