仅在最后一条评论上爆炸,跳过#inside变量

问题描述 投票:2回答:2

像这样的示例值:

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"

https://regex101.com/r/IpcEPU/1

php regex
2个回答
2
投票

给定样本输入,您只需要从空间哈希中删除子串到行尾。

代码:(Demo

$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);

如果您的引用文本中可能包含空格哈希子串,那么(*SKIP)(*FAIL)将通过取消这些值的参数来提供帮助。

模式:'~(["']).*?\1(*SKIP)(*FAIL)| #.*~'替换:''(空字符串)

这将确保不匹配/删除单引号或双引号包装的空间哈希子字符串。


1
投票

找到一个正则表达式的解决方案:

/(?=(^(.*)[ ])(?=#[ a-z0-9]+))|(?=(^(.*))+)/i

它将仅解析值并跳过任何类型的注释。

https://regex101.com/r/dFVhjr/1

如果有任何改进的想法,欢迎。

© www.soinside.com 2019 - 2024. All rights reserved.