有什么方法可以实现以下目标吗?我需要接受这个$query并将其拆分为不同的元素(原因是我必须重新处理插入查询)。正如您所看到的,这将适用于常规字符串块或数字,但不适用于字符串中出现数字的地方。有没有一种方法可以说出|''d,但不能说出它在"带引号的字符串"中的位置?
$query = "('this is''nt very, funny (I dont think)','is it',12345,'nope','like with 2,4,6')";
$matches = preg_split("#',|'d,#",substr($query,1,-1));
echo $query;
print'<pre>[';print_r($matches);print']</pre>';
因此,为了明确预期结果:
0:'this is''nt very, funny (I dont think)'
1:'it is'
2:12345
3:'nope'
4:'like with 2,4,6'.
**此外,我不介意每个字符串是否被引用而不是引用——我可以自己重新引用它们。
可以(*SKIP)(*F)位于单引号内的部件,并在外匹配,
'(?:'''|[^'])*'(*SKIP)(*F)|,
单引号内的(?:'''|[^'])
匹配转义的''
或非单引号字符。
请参阅regex101.com 上的测试
$query = "('this is''nt very, funny (I dont think)','is it',12345,'nope','like with 2,4,6')";
$matches = preg_split("~'(?:'''''|[^'])*'(*SKIP)(*F)|,~", substr($query,1,-1));
print_r($matches);
输出到(在eval.in测试)
Array
(
[0] => 'this is''nt very, funny (I dont think)'
[1] => 'is it'
[2] => 12345
[3] => 'nope'
[4] => 'like with 2,4,6'
)
不完全确定,如果这就是你的意思:)
('(?:(?!(?<!'')').)*')|('d+)
试试这个。抓住捕获的。每个字符串也被引用。请参阅演示。
http://regex101.com/r/dK1xR4/3
您可以尝试通过preg_match_all
进行匹配,而不是拆分。
<?php
$data = "('this is''nt very, funny (I dont think)','is it',12345,'nope','like with 2,4,6')";
$regex = "~'(?:'''''|[^'])+'|(?<=,|'()[^',)]*(?=,|'))~";
preg_match_all($regex, $data, $matches);
print_r($matches[0]);
?>
输出:
Array
(
[0] => 'this is''nt very, funny (I dont think)'
[1] => 'is it'
[2] => 12345
[3] => 'nope'
[4] => 'like with 2,4,6'
)
如果您不介意使用preg_match
,那么解决方案可能是这样的。此regex使用带否定断言(?<!'''')
的lookbacking,它将匹配引号中不带斜杠的字符串,并且与竖线的交替确保较大匹配的数字将被忽略。
$query = "('this is''nt very, funny (I dont think)','is it',12345,'nope','like with 2,4,6',6789)";
preg_match_all( "/(?<!'''')''.+?(?<!'''')''|'d+/", substr( $query, 1, -1 ), $matches );
print_r( $matches );
/* output:
Array (
[0] => Array
(
[0] => 'this is''nt very, funny (I dont think)'
[1] => 'is it'
[2] => 12345
[3] => 'nope'
[4] => 'like with 2,4,6'
[5] => 6789
)
)
*/
,(?=(?:[^']*'[^']*')*[^']*$)
试试这个。这将根据您的需求进行拆分。替换为'n
。请参阅演示。
http://regex101.com/r/dK1xR4/4