Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip everything in string after the second "-" character that occurs?

Tags:

php

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

In this case i would want Saturday to be removed along with the last - so somehow strip : "- Saturday"

Any help is very much appreciated :) I can only seem to get everything to be removed after the first "-".

like image 841
samirah Avatar asked Jun 17 '11 00:06

samirah


People also ask

How to remove everything in a string after a character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do I trim a string after a specific character in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do you return part of a string after a certain character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character.

How do you remove portion of a string before a certain character in PHP?

You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.


2 Answers

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));
like image 88
Rasika Avatar answered Nov 10 '22 04:11

Rasika


How about some explosions:

$parts = explode( '-', "Today is - Friday and tomorrow is - Saturday" );
echo $parts[0].'-'.$parts[1];
like image 24
Bailey Parker Avatar answered Nov 10 '22 04:11

Bailey Parker