我如何摆脱preg_split结果中的尾随空格而不使用preg_replace先从$test字符串中删除所有空格?
$test = 'One , Two, Thee ';
$test = preg_replace('/\s+/', ' ', $test);
$pieces = preg_split("/[,]/", $test);
Run Code Online (Sandbox Code Playgroud) 我从文本文件中读入并分配变量,就好像它们是带有列表的数组一样。我通过在换行符上爆炸来做到这一点。
但是,我还想修剪输入两侧的任何空白。根据我的理解和测试,这正是 trim() 所做的。
我想缩短它,以便它减少重复和更容易阅读。
$config = file_get_contents('scripts/secure/config.txt');
list($host, $dbname, $username, $password) = explode ("\n", $config);
$host = trim($host);
$dbname = trim($dbname);
$username = trim($username);
$password = trim($password);
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的方法,但似乎都不起作用。我上面的方法确实有效,但我正在寻找一种单行方法。
表单上的输入字段接受逗号分隔值的列表。
无论用户在每个逗号后输入空格one, two, three还是不带空格,如何将这些值转换为数组one,two,three?
基本上,我想结合
$myArray = explode(', ', $myString);
和
$myArray = explode(',', $myString);