I find the control and brevity of a regex pattern to be most attractive for this task.
Match zero or more non-hyphens, then a hyphen (N amount of times; 2 in this case), resetting the full string match with \K
before the latest hyphen matched, then match the remaining characters.
This approach will not remove any characters if there are less then N hyphens in the string.
Code: (Demo)
$string = "Today is - Friday and tomorrow is - Saturday";
var_export(
preg_replace('/(?:[^-]*\K-){2}.*/', '', $string)
);
If you want to trim trailing spaces after the second hyphen, you can add that to the pattern instead of calling rtrim()
on the returned string. (Demo)
var_export(
preg_replace('/(?:[^-]*?\K\s*-){2}.*/', '', $string)
);
I don't personally enjoy the idea of making three function calls to generate a temporary array, then only keep upto the first two elements, then re-joining the array to be a hyphen-delimited string, but if you hate regex so much to want that approach you should limit the number of explosions to be N+1 so that no unnecessary elements are created. (Demo)
var_export(
implode('-', array_slice(explode('-', $string, 3), 0, 2))
);