Php 除了括号中的逗号外,如何在逗号上拆分?
我想这样分开: 之前: 之后:Php 除了括号中的逗号外,如何在逗号上拆分?,php,split,Php,Split,我想这样分开: 之前: 之后: 如何拆分它?这次正则表达式没有帮助,因此您必须遍历字符 事实上,正则表达式并不是很了解上下文。因此。这就是为什么我们最好自己遍历字符串 function magic_split($str) { $sets = array(''); // Sets of strings $set_index = 0; // Remember what index we’re writing to $brackets_depth = 0; // Ke
如何拆分它?这次正则表达式没有帮助,因此您必须遍历字符 事实上,正则表达式并不是很了解上下文。因此。这就是为什么我们最好自己遍历字符串
function magic_split($str) {
$sets = array(''); // Sets of strings
$set_index = 0; // Remember what index we’re writing to
$brackets_depth = 0; // Keep track if we’re in brackets (or not)
// Iterate through entire string
for($i = 0; $i < strlen($str); $i++) {
// Skip commas if we’re not in brackets
if($brackets_depth < 1 && $str[$i] === ',') continue;
// Add character to current list
$sets[$set_index] .= $str[$i];
// Store brackets depth
if($str[$i] === '(') $brackets_depth++;
if($str[$i] === ')') $brackets_depth--;
if(
$i < strlen($str) - 1 && // Is a next char available?
$str[$i+1] === ',' && // Is it a comma?
$brackets_depth === 0 // Are we not in brackets?
) $sets[++$set_index] = ''; // Add new set
}
return $sets;
}
$input = 'TEST_A, TEST_B, TEST_C (with A, B, C), TEST_D';
$split = magic_split($input);
函数魔法分割($str){
$sets=数组(“”);//字符串集
$set_index=0;//还记得我们在写什么索引吗
$括号_depth=0;//跟踪我们是否在括号内(或不在括号内)
//遍历整个字符串
对于($i=0;$i
此问题的正确解决方案将完全取决于您用于标识单个元素的规范
如果您希望每个问题都以TEST\uuu
开头,那么您可以用正则表达式非常简单地解决它:
$input = 'TEST_A, TEST_B, TEST_C (with A, B, C), TEST_D';
$matches = preg_split('/,\s*(?=TEST_)/', $input);
var_dump($matches);
输出:
array(4) {
[0]=>
string(6) "TEST_A"
[1]=>
string(6) "TEST_B"
[2]=>
string(21) "TEST_C (with A, B, C)"
[3]=>
string(6) "TEST_D"
}
array (
0 => 'TEST_A',
1 => 'TEST_B',
2 => 'TEST_C (with A, B, C)',
3 => 'TEST_D',
)
这会在下一项的开头使用测试是否存在test.
来拆分逗号后跟空格的字符串。要匹配的:
- 一个不包含左括号和右括号的单词:[^(,]+
- 括号之间的表达式:\([^(]+\)
- 或者不返回匹配项,则变为:(?:\([^(]+\)?)
- 昏迷,后跟一些空格:,[\s]*
$ar=preg_split("#([^(,]+(?:\([^(]+\))?),[\s]*#", "$input,", -1,
PREG_SPLIT_DELIM_CAPTURE |PREG_SPLIT_NO_EMPTY)
编辑:如果括号外没有昏迷,则该选项无效。
您必须在$input之后添加一个额外的coma,如上面修改的。您只需在逗号空间上分解,忽略括号内的任何逗号空间。
(*SKIP)(*FAIL)
将使用所有括号表达式并将其丢弃,以便它们不用作分隔符
代码:()
输出:
array(4) {
[0]=>
string(6) "TEST_A"
[1]=>
string(6) "TEST_B"
[2]=>
string(21) "TEST_C (with A, B, C)"
[3]=>
string(6) "TEST_D"
}
array (
0 => 'TEST_A',
1 => 'TEST_B',
2 => 'TEST_C (with A, B, C)',
3 => 'TEST_D',
)
输出是文本、HTML、数组还是其他形式?答案将帮助您决定是否使用换行符(“\n”),HTML分隔符,或其他方法。你试过什么吗?@Rizier123是的,我试过。但除了逗号,我不能拆分brackets@Dave我知道正则表达式。但是,我不能让代码完美地工作。这很好。但是,这段代码删除了括号中的逗号。:(因此,我添加了一些代码[如果($方括号_depth==0&&$str[$I]==',')继续;]然后,它工作得很好。谢谢!@WebEngine我的道歉,你完全正确。如果有人碰巧遇到这个问题,我已经修改了代码:)它非常好!但是,如果$input是“TEST(A,B,C)”,它将返回“TEST('/'A'/'B'/'C)”:(哦,你是对的。只需在右侧添加一个额外的昏迷。
array (
0 => 'TEST_A',
1 => 'TEST_B',
2 => 'TEST_C (with A, B, C)',
3 => 'TEST_D',
)