您的位置:首页 > 编程语言 > PHP开发

PHP 将逗号、空格、回车分隔的字符串转换为数组的函数

2018-10-12 13:53 2231 查看
我们在搜索一些东西时会经常遇到可以通过空格隔开来达到输入多个条件的目的。今天正好项目中遇到了这个情况,就写了一个函数,将多个条件放到数组里。目前支持空格、逗号(中英文)、回车分割,如不能满足需求,看下这个函数修改一下应该就可以了

<?php
/**
* transform ' hello, world !' to array('hello', 'world')
*/
function strsToArray($strs) {
$result = array();
$array = array();
$strs = str_replace(',', ',', $strs);
$strs = str_replace("n", ',', $strs);
$strs = str_replace("rn", ',', $strs);
$strs = str_replace(' ', ',', $strs);
$array = explode(',', $strs);
foreach ($array as $key => $value) {
if ('' != ($value = trim($value))) {
$result[] = $value;
}
}
return $result;
}
//test
$strs = 'Code is poetry! WTF!';
var_dump(strsToArray($strs));

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: