0

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?

carter
  • 5,074
  • 4
  • 31
  • 40

7 Answers7

3
// 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);
nice ass
  • 16,471
  • 7
  • 50
  • 89
2

You can also do:

$str = 'some_long_string';
echo explode( '_', $str, 2)[1]; // long_string
nickb
  • 59,313
  • 13
  • 108
  • 143
2

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.

Fabi
  • 973
  • 7
  • 18
  • Yes! You are correct! This is exactly what I was looking for. Strange I couldn't find it with my searches. :) – carter May 03 '13 at 02:01
  • This fails when you have more than one of the delimiter in the string. You need to specify the limit parameter [as I did in my answer](http://stackoverflow.com/a/16348360/862594). – nickb May 03 '13 at 02:43
1

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

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
1

Just use strstr

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

Output

Ramdom#String
Baba
  • 94,024
  • 28
  • 166
  • 217
1

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)

docTRIN
  • 71
  • 1
  • 4
-1

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);
nickb
  • 59,313
  • 13
  • 108
  • 143
carter
  • 5,074
  • 4
  • 31
  • 40
  • I put this into production already because it does exactly what I want... It selects all characters to the right of a delimiter. The better method is "explode()" however. – carter May 03 '13 at 02:02