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

时间:2018-03-04 13:21:43

标签: 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($matches);

问题在于没有'#comment'打印

结果应该在第一个数组上:

fdsfsf345#3gt#$%3^#$T$#tr43r43
test spaces
"test spaces"

"fdsfsf345#3gt#$%3^#$T$#tr43r43"
"test spaces"

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

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

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

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