我需要使用分隔符将一个字符串分成两部分。我所要做的就是使用 explode() 函数……我知道。
但这是我正在尝试做的事情:我需要使用定界符拆分字符串,但如果定界符包含在引号中,则应将其忽略。
假设我的分隔符是连字符 (-),我需要拆分以下字符串:
The ‘big-yellow’ house-is near the lake
必须忽略第一个连字符,因为它在引号中,因此我最终会得到如下两个字符串:
1. The ‘big-yellow’ house
2. is near the lake
而且它还应该能够检测转义引号。
E.g.: He doesn\’t like it because-he isn\’t from here.
在这种情况下,连字符不在引号内,因此应该拆分字符串。
有什么想法吗?
最佳答案
你可以使用
'[^'\\]*(?:\\.[^'\\]*)*'(*SKIP)(?!)|-
参见 regex demo
'[^'\\]*(?:\\.[^'\\]*)*'
部分将匹配单引号和任何转义实体,并且 ( *SKIP)(?!)
将强制正则表达式引擎在最后一个索引 + 匹配长度之后继续搜索匹配项。
这是一个 IDEONE demo :
$re = "/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'(*SKIP)(?!)|-/";
$strs = array("The 'big-yellow' house-is near the lake", "He doesn\'t like it because-he isn\'t from here.");
foreach ($strs as $str) {
$result = preg_split($re, $str);
print_r($result);
}
输出:
Array( [0] => The 'big-yellow' house [1] => is near the lake)
and Array( [0] => He does\n't喜欢它是因为 [1] => 他不是这里的人。)
。
关于php - 使用php检测引号外的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35160796/