Php 仅在最后一条注释时分解,跳过#内部变量
示例值如下所示:Php 仅在最后一条注释时分解,跳过#内部变量,php,regex,Php,Regex,示例值如下所示: fdsfsf345#3gt#$%3^#$T$#tr43r43 test spaces "test spaces" "fdsfsf345#3gt#$%3^#$T$#tr43r43" #comment "test spaces" #comment 剧本: $re = '/(.*)(?:\"|\'|)(?: )#?(.*)|(.*)/mi'; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); var_dump($mat
fdsfsf345#3gt#$%3^#$T$#tr43r43
test spaces
"test spaces"
"fdsfsf345#3gt#$%3^#$T$#tr43r43" #comment
"test spaces" #comment
剧本:
$re = '/(.*)(?:\"|\'|)(?: )#?(.*)|(.*)/mi';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
一个问题是,不带“#comment”的行会打印出来
结果应在第一个数组上:
fdsfsf345#3gt#$%3^#$T$#tr43r43
test spaces
"test spaces"
"fdsfsf345#3gt#$%3^#$T$#tr43r43"
"test spaces"
找到了使用正则表达式的解决方案:
/(?=(^(.*)[ ])(?=#[ a-z0-9]+))|(?=(^(.*))+)/i
它将只解析值,并使用任何类型注释跳过
如果您有任何改进的想法,欢迎使用。给定您的示例输入,您只需要删除从空格散列到行尾的子字符串 代码:()
如果引用的文本中可能有空格哈希子字符串,则取消这些值的资格将有助于
(*SKIP)(*FAIL)
模式:“~([”).*?\1(*跳过)(*失败)|#.*”
替换:”
(空字符串)
这将确保不匹配/删除单引号或双引号包装的空间哈希子字符串。
#
在第二个命名捕获组的空间是可选的之后,它应该是强制的。您希望在这里实现什么?(*跳过)(*失败)
或lookarounds出现在我的脑海中,但预期的输出是什么?顺便说一句,点星汤似乎效率很低。我想如果行中有“#comment”,它会将它们从行中删除。问题是值为“#”,但我不想分解它们。@MarinSagovac:像这样:?否则,请给出更现实的输入示例。您的示例在这行的末尾只有#注释
。你的意思是当它匹配时不匹配吗?或者你可以将它与匹配。
$array = [
'bar',
'fdsfsf345#3gt#$%3^#$T$#tr43r43',
'test spaces',
'"test spaces"',
'"fdsfsf345#3gt#$%3^#$T$#tr43r43" #comment',
'test spaces" #comment',
'bar',
'""',
'""""',
'foo1 #comment2',
'"with space value" #comment',
'with quote value\'',
'somestringstart',
'with spaces" # a comment',
'bar'
];
$result=preg_replace('~ #.*~','',$array);
var_export($result);