字符串中的单独文本

时间:2017-12-28 21:13:54

标签: php

我从我的mysql数据库中获取此结果:

$_SESSION['svrdata'] = 
 187.14.12.48:admin:root:/home/svr/,
 187.14.12.72:admin:root:/home/svr2/, 
 187.14.12.2:admin:root:/home/svr3/

187.14.12.x = IP
admin = login
root = password
/home/svr/ = directory

如何在下拉菜单中只放置这些IP地址?

$myString = $_SESSION['svrdata']; //
$myArray = explode(',', $myString);
echo '<select multiple="multiple" name="field[]" id="field[]"">';
echo '<option selected="true" value="0" disabled>Select</option>';

$string = explode(':', $myArray);
foreach ($string as $line) {
echo '<option value='.$line.'>'.$line.'</option>';
}
echo '</select>';

没有错误,但仍然没有显示任何内容。我该如何解决? 谢谢!

1 个答案:

答案 0 :(得分:1)

你可以使用explode http://php.net/manual/en/function.explode.php

$str = '187.14.12.48:admin:root:/home/svr/'; 
$string = explode(':', $str);

print_r($string);

<强>更新:

$myString = ' 187.14.12.48:admin:root:/home/svr/, 187.14.12.72:admin:root:/home/svr2/,  187.14.12.2:admin:root:/home/svr3/'; 
$ipAddress = [];
$myArray = explode(',', $myString);
foreach ($myArray as $array) {
    $tempArray = explode(':', $array);
    $ipAddress[] =  $tempArray[0];
}
echo '<select multiple="multiple" name="field[]" id="field[]"">';
echo '<option selected="true" value="0" disabled>Select</option>';

$string = explode(':', $myArray);
foreach ($ipAddress as $line) {
echo '<option value='.$line.'>'.$line.'</option>';
}
echo '</select>';

<强>说明: 循环遍历$myArray,然后将:分解为新的数组,该数组称为$ipAddress,因此它只包含IP地址。