Question

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?

Était-ce utile?

La solution 2

You can also do:

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

Autres conseils

// 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);

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.

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

Just use strstr

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

Output

Ramdom#String

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)

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top