简体   繁体   中英

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?

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

You can also do:

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

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.

使用strpos查找特定字符的位置,然后使用substr抓住其后的所有字符。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM