[英]How to select all characters to the right of a specific character in a string - PHP
我花了很長時間試圖弄清楚! 當我不知道會有多少個字符時,如何選擇字符串中某個特定字符右邊的所有字符?
// 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);
您也可以這樣做:
$str = 'some_long_string';
echo explode( '_', $str, 2)[1]; // long_string
我不確定這是否適合您的需求,但是:
$string = explode(',','I dont know how to, get this part of the text');
$ string [1]不會總是在分隔符的右邊嗎? 除非字符串中有多個相同的字符串,否則...如果不是您要的字符串,請對不起。
使用strpos
查找特定字符的位置,然后使用substr
抓住其后的所有字符。
只需使用strstr
$data = 'Some#Ramdom#String';
$find = "#" ;
$string = substr(strstr($data,$find),strlen($find));
echo $string;
輸出量
Ramdom#String
您必須使用帶負起始整數的substr
$startingCharacter = 'i';
$searchString = 'my test string';
$positionFromEnd = strlen($searchString)
- strpos($searchString, $startingCharacter);
$result = substr($searchString, ($positionFromEnd)*-1);
或功能中:
function strRightFromChar($char, $string) {
$positionFromEnd = strlen($string) - strpos($string, $char);
$result = substr($string, ($positionFromEnd)*-1);
return $result;
}
echo strRightFromChar('te', 'my test 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.