我在PHP中有以下字符串。
:guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP
我需要从字符串中创建这些变量:
$nick = guest
$user = lbjpewueqi
$host = AF8A326D.E0B4A40D.F85DC93A.IP
用于执行此操作的最佳功能是什么?
理想情况下,我想创建某种函数,以便我可以将字符串传递给它,以及我想要返回的部分。
例如:
$string = "guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP";
echo stringToPart($string, nick);
guest
echo stringToPart($string, nick);
lbjpewueqi
echo stringToPart($string, host);
AF8A326D.E0B4A40D.F85DC93A.IP
答案 0 :(得分:0)
也许这段代码对您有帮助
$p = '/[:!@]/';
$s = ":guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP";
print_r( preg_split( $p, $s ), 1 );
答案 1 :(得分:0)
以下内容应该是你想要的。
$pattern = "/[:!@]/";
$subject = ":guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP";
print_r(preg_split($pattern, $subject));
模式是指定要拆分的字符,因此如果有其他实例需要考虑传入的不同字符串,理论上你可以在这里有任意数量的字符。
要返回值而不是仅打印然后再到屏幕,请使用:
$pattern = "/[:!@]/";
$subject = ":guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP";
$result = preg_split($pattern, $subject));
$nick = $result[1];
$user = $result[2];
$host = $result[3];
答案 2 :(得分:0)
你可以声明一个这样的函数:
$s = ":guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP";
function stringToPart($str, $part) {
$pat['nick'] = '/:(.*)!/';
$pat['user'] = '/.*!(.*)@/';
$pat['host'] = '/@(.*)/';
preg_match($pat[$part], $str, $m);
if (count($m) > 1) return $m[1];
return null;
}
echo stringToPart($s,'nick')."\n";
echo stringToPart($s,'user')."\n";
echo stringToPart($s,'host')."\n";
答案 3 :(得分:0)
stringToPart(':guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP','nick');
function stringToPart($string, $type){
$result['nick']= substr($string,strpos($string,':')+1,(strpos($string,'!')-strpos($string,':')-1));
$result['user']= substr($string,strpos($string,'!')+1,(strpos($string,'@')-strpos($string,'!')-1));
$result['host']= substr($string,strpos($string,'@')+1);
return $result[$type];
}
答案 4 :(得分:0)
另一个版本:
function stringToPart($string, $part) {
if (preg_match('/^:(.*)!(.*)@(.*)/', $string, $matches)) {
$nick = $matches[1];
$user = $matches[2];
$host = $matches[3];
return isset($$part) ? $$part : null;
}
}
比preg_split解决方案更严格 - 它会检查分隔符顺序。
答案 5 :(得分:0)
<?php
function stringToPart($string, $key)
{
$matches = null;
$returnValue = preg_match('/:(?P<nick>[^!]*)!(?P<user>.*?)@(?P<host>.*)/', $string, $matches);
if (isset($matches[$key]))
{
return $matches[$key];
} else
{
return NULL;
}
}
$string = ':guest!lbjpewueqi@AF8A326D.E0B4A40D.F85DC93A.IP';
echo stringToPart($string, "nick");
echo "<br />";
echo stringToPart($string, "user");
echo "<br />";
echo stringToPart($string, "host");
echo "<br />";
?>