Strip all characters in a string starting from the second occurring hyphen
Asked Answered
C

7

14

How can I strip everything in a string after the character - has occurred for the second time?

For example: Today is - Friday and tomorrow is - Saturday

I want Saturday to be removed along with the last hyphen: - Saturday

I can only seem to get everything to be removed after the first -.

The expected result is: Today is - Friday and tomorrow is

Corpora answered 17/6, 2011 at 0:43 Comment(0)
T
15

Edit: Please note as noted by @mickmackusa below, this will return an empty string if there are less than two hyphens. End Edit.

Use strpos to find the first occurrence and use it again to find the point to end using the offset option with the value from previous. Then use substr.

$newstr = substr($str, 0, strpos($str, '-', strpos($str, '-')+1));
Trace answered 17/6, 2011 at 0:46 Comment(1)
This answer will destroy all characters in the string if there are less than 2 hyphens in the input string. 3v4l.org/vB1SU and 3v4l.org/hum1d Use with caution.Olpe
R
14

How about some explosions:

$parts = explode( '-', "Today is - Friday and tomorrow is - Saturday" );
echo $parts[0].'-'.$parts[1];
Riptide answered 17/6, 2011 at 0:48 Comment(1)
This unexplained answer will make unlimited unnecessary/unused elements while exploding. If the string doesn't contain a hyphen, then PHP will complain about trying to access an element that doesn't exist.Olpe
H
6

Another way with strtok:

$newStr = strtok($str, '-') . '-' . strtok('-');

DEMO

Hedberg answered 17/6, 2011 at 0:55 Comment(2)
This one is great! Needs a small explanation, how does "strtok()" works, cause this was discovery for me too. But result is nice and shiny! From php.net: Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string.Covenantee
This unexplained answer is not safe to use if the number of hyphens is unknown (might be zero). Proof: 3v4l.org/KkF0tOlpe
P
3

For others with the same problem; I used this compact solution that is easy to adjust.

$str = 'Today is - Friday and tomorrow is - Saturday';

$sliceWith = "-"; // character to split by
$beginWith = 0; // 1 removes before first match, 0 will not
$splitAfter = 2; // number of matches to keep

$result = implode($sliceWith, array_slice(explode($sliceWith, $str), $beginWith, $splitAfter));

echo $result; // You might want to use trim($result)
Paleoclimatology answered 16/12, 2016 at 12:17 Comment(0)
M
0

You could use explode() to split the string at each occurrence of "-". EG:

$str = "Today is - Friday and tomorrow is - Saturday"
$parts = explode(" - ", $str);

Would leave you with:

$parts = ["Today is", "Friday and tomorrow is", "Saturday"]

And as such the bit you want is going to be the first two items with a "-" in the middle, so we can pop the last element from the array and join the rest:

array_pop($parts);
$result = implode(" - ", $parts);

Which gives:

$result == "Today is - Friday and tomorrow is";
Mongoloid answered 17/6, 2011 at 0:55 Comment(1)
This answer is implement inaccurate logic. It is not truncating on the 2nd hyphen, it is truncating on the last occurring hyphen (which is not what is clearly required in the question). For any case when the input has more than 2 hyphens, it is incorrect 3v4l.org/uBQFe For any case when the input has less than 2 hyphens, it is incorrect 3v4l.org/CENlo This answer is the correct solution to a different question and is not safe for general use for this task.Olpe
O
0

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))
);
Olpe answered 31/5, 2023 at 2:12 Comment(0)
I
-1
 $string = "Today is - Friday and tomorrow is - Saturday";
 $first_dash = strpos($string, '-');
 $second_dash = strpos($string, '-', $first_dash+1);
 $new_string = substr($string, $second_dash+1);

strpos

substr

Iconolatry answered 17/6, 2011 at 0:49 Comment(1)
This unexplained answer damages the input string when there are less than 2 hyphens in the string. 3v4l.org/6PRoK and 3v4l.org/PooWa This answer is not safe for general use.Olpe

© 2022 - 2024 — McMap. All rights reserved.