我喜歡MySQL中的SUBSTRING_INDEX
函數,尤其是因爲您可以使用負指標從字符串的右側開始搜索。PHP:相當於MySQL的函數SUBSTRING_INDEX?
在PHP中是否有這個函數的等價物? (或一個簡單的方法有一些代碼來做到這一點)
我喜歡MySQL中的SUBSTRING_INDEX
函數,尤其是因爲您可以使用負指標從字符串的右側開始搜索。PHP:相當於MySQL的函數SUBSTRING_INDEX?
在PHP中是否有這個函數的等價物? (或一個簡單的方法有一些代碼來做到這一點)
沒有單一的庫函數讓你這個相同的功能,但你可以得到一個班輪:
$str = "www.mysql.com";
echo implode('.', array_slice(explode('.', $str), 0, 2)); // prints "www.mysql"
echo implode('.', array_slice(explode('.', $str), -2)); // prints "mysql.com"
輕鬆地把它變成功能:
function substring_index($subject, $delim, $count){
if($count < 0){
return implode($delim, array_slice(explode($delim, $subject), $count));
}else{
return implode($delim, array_slice(explode($delim, $subject), 0, $count));
}
}
function substring_index($subject, $delim, $count){
if($count < 0){
return implode($delim, array_slice(explode($delim, $subject), $count));
}else{
return implode($delim, array_slice(explode($delim, $subject), 0, $count));
}
}
我覺得
string strstr (string $haystack , mixed $needle [, bool $before_needle = false ])
是適合您的php功能。
的strstr - 查找字符串
<?php
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
我很好奇和測試使用預浸料/匹配設置的另一種方法的第一次出現,然後重構它以允許任何數量的分隔符/計數。我在計數檢查中添加了其他示例正在使用的內容,但我可能還會推薦對分隔符字段進行某種消毒。
function substring_index($subject, $delim, $count){
if($count < 0){
$notRe = '[^\\'.$delim.']*';
$elem = array();
for($x=1;$x<=$count;$x++){
array_push($elem,$notRe);
}
$re = '/^('.implode('\\'.$delim,$elem).')/';
preg_match($re, $subject,$m);
if(count($m) == 2) {
return $m[1];
}
}
}
對於那些想'substr',讀的['SUBSTRING_INDEX']的定義(http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index ) –