carter
carter

Reputation: 5432

How to select all characters to the right of a specific character in a string - PHP

I spent a long time trying to figure this out! How do I select all the characters to the right of a specific character in a string when I don't know how many characters there will be?

Upvotes: 0

Views: 3479

Answers (7)

docTRIN
docTRIN

Reputation: 91

You have to use substr with a negative starting integer

$startingCharacter = 'i';
$searchString = 'my test string';
$positionFromEnd = strlen($searchString)
    - strpos($searchString, $startingCharacter);
$result = substr($searchString, ($positionFromEnd)*-1);

or in a function:

function strRightFromChar($char, $string) {
    $positionFromEnd = strlen($string) - strpos($string, $char);
    $result = substr($string, ($positionFromEnd)*-1);
    return $result;
}
echo strRightFromChar('te', 'my test string');

(Note that you can search for a group of characters as well)

Upvotes: 1

Baba
Baba

Reputation: 95101

Just use strstr

$data = 'Some#Ramdom#String';
$find = "#" ;
$string = substr(strstr($data,$find),strlen($find));
echo $string;

Output

Ramdom#String

Upvotes: 1

nice ass
nice ass

Reputation: 16709

// find the position of the first occurrence of the char you're looking for
$pos = strpos($string, $char);

// cut the string from that point
$result = substr($string, $pos + 1);

Upvotes: 3

Fabi
Fabi

Reputation: 973

I'm not sure this would fit your needs, but :

$string = explode(',','I dont know how to, get this part of the text');

Wouldn't $string[1] always be the right side of the delimiter? Unless you have more than one of the same in the string... sorry if it's not what you're looking for.

Upvotes: 2

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

Use strpos to find the position of the specific character, and then use substr to grab all the characters after it.

Upvotes: 1

nickb
nickb

Reputation: 59699

You can also do:

$str = 'some_long_string';
echo explode( '_', $str, 2)[1]; // long_string

Upvotes: 2

carter
carter

Reputation: 5432

Assuming I want to select all characters to the right of the first underscore in my string:

$stringLength = strlen($string_I_want_to_strip);
$limiterPos = strpos($string_I_want_to_strip, "_");
$reversePos = $limiterPos - $stringLength + 1;
$charsToTheRight = substr($string_I_want_to_strip, $reversePos, $limiterPos);

Upvotes: -1

Related Questions