Asked  7 Months ago    Answers:  5   Viewed   35 times

I'm just wondering how I could remove everything after a certain substring in PHP


Posted On April 6th By Some Dude

I'd like to have it so that it removes all the text including, and after, the sub string "By"



$variable = substr($variable, 0, strpos($variable, "By"));

In plain english: Give me the part of the string starting at the beginning and ending at the position where you first encounter the deliminator.

Wednesday, March 31, 2021
answered 7 Months ago

A regex would be simplest:

$input = 'foo_left.jpg';
if(!preg_match('/_(left|right|center)/', $input, $matches)) {
    // no match

$pos = $matches[0]; // "_left", "_right" or "_center"

See it in action.


For a more defensive-minded approach (if there might be multiple instances of "_left" and friends in the filename), you can consider adding to the regex.

This will match only if the l/r/c is followed by a dot:

preg_match('/(_(left|right|center))./', $input, $matches);

This will match only if the l/r/c is followed by the last dot in the filename (which practically means that the base name ends with the l/r/c specification):

preg_match('/(_(left|right|center))\.[^\.]*$/', $input, $matches);

And so on.

If using these regexes, you will find the result in $matches[1] instead of $matches[0].

Wednesday, March 31, 2021
answered 7 Months ago

This can't work properly. Stored with Unicode there are many more Characters than with ANSI. So if you "convert" to ANSI, you will loose lots of charackters.

You can use Unicode (UTF-8) charset with htmlentities:

string htmlentities ( string $string [, int $flags = ENT_COMPAT [, string $charset [, bool $double_encode = true ]]] )

htmlentities($myString, ENT_COMPAT, "UTF-8"); should work.

Thursday, August 5, 2021
answered 3 Months ago
new_str = str.slice(0..(str.index('blah')))

alt text

Monday, August 9, 2021
answered 3 Months ago

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().


>>> x = ''
>>> print x.rsplit('-', 1)[0]
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
Saturday, September 4, 2021
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :