Hii朋友, 我在php中有字符串,如
现在我想将域名(粗体文字)拆分为
表示我想分割用户名和域名。
所以请帮助我。
答案 0 :(得分:1)
您可以尝试:
$inputs = ['abc.com', 'abc.name.com', 'abc.xyz.name.org'];
foreach ($inputs as $input) {
$parts = explode('.', $input);
$right = [array_pop($parts)];
if (count($parts) > 1) {
$right[] = array_pop($parts);
}
$output = [
'left' => implode('.', $parts),
'right' => implode('.', $right),
];
var_dump($output);
}
输出:
array (size=2)
'left' => string 'abc' (length=3)
'right' => string 'com' (length=3)
array (size=2)
'left' => string 'abc' (length=3)
'right' => string 'com.name' (length=8)
array (size=2)
'left' => string 'abc.xyz' (length=7)
'right' => string 'org.name' (length=8)
答案 1 :(得分:1)
在explode()之后使用array_pop()函数:
$vars = explode('.', $string);
if ( count($vars) == 3 ) {
$string2 = $vars[1] . '.' . $vars[2];
$string1 = $vars[0];
}
if ( count($vars) == 2 ) {
$string2 = $vars[1];
$string1 = $vars[0];
}
// Or you may use
$vars = explode('.', $string);
if ( count($vars) == 3 ) {
$string2 = $vars[1] . '.' . $vars[2];
$string1 = $vars[0];
}
if ( count($vars) == 2 ) {
$string2 = array_pop($vars);
$string1 = array_pop($vars);
}
检查pop.net并在php.net中爆炸
答案 2 :(得分:0)
这应该可以解决问题。我尽量让它变得冗长。 Online test
<?php
function get_last_dot_occurence ($url ) {
$fullArray = explode('.', $url);
$newArray = "";
switch (count($fullArray)) {
case 0:
break;
case 1:
$newArray = $url;
break;
case 2:
$newArray = array("string1" => $fullArray[0], "string2" => $fullArray[1]);
break;
default:
$string1 = "";
for ($i=0; $i < count($fullArray)-2; $i++) {
$string1 .= $fullArray[$i];
if($i != count($fullArray)-3)
$string1 .= '.';
}
$string2 = $fullArray[count($fullArray)-2].'.'.$fullArray[count($fullArray)-1];
$newArray = array("string1" => $string1, "string2" => $string2);
break;
}
return $newArray;
}
print_r(get_last_dot_occurence("abc.com"));
print_r(get_last_dot_occurence("abc.name.com"));
print_r(get_last_dot_occurence("abc.xyz.name.org"));