我正试图从文本中获取t("
和")
或t('
和')
之间的所有字符串。
我提出了regexp /[^t'(("|'')]*(?=("|'')'))/
,但当字符"t"不在"("之前时,它并没有忽略它。
例如:
$str = 'This is a text, t("string1"), t(''string2'')';
preg_match_all('/[^t'(("|'')]*(?=("|'')'))/', $str, $m);
var_dump($m);
返回ring1
和ring2
,但我需要得到string1
和string2
。
你也可以考虑一下。
您需要为每个正则表达式使用单独的正则表达式。
(?<=t'(").*?(?="'))|(?<=t'('').*?(?=''))
演示
代码:
$re = "/(?<=t''('").*?(?='"''))|(?<=t''(''').*?(?='''))/m";
$str = "This is a text, t('"string1'"), t('string2')";
preg_match_all($re, $str, $matches);
或
将捕获组与'K
一起使用
t'((['"])'K.*?(?='1'))
演示
'K
在最终打印时丢弃先前匹配的字符。
使用以下模式只需几步即可完成:
$pattern = '~t'((?|"([^"''']*+(?s:'''.[^"''']*)*+)"')|''([^''''']*+(?s:'''.[^''''']*)*+)'''))~';
if (preg_match_all($pattern, $str, $matches))
print_r($matches[1]);
它有点长,重复性强,但速度快,可以处理转义引号。
详细信息:
t'(
(?| # Branch reset feature allows captures to have the same number
"
( # capture group 1
[^"'']*+ # all that is not a double quote or a backslash
(?s: # non capturing group in singleline mode
''. # an escaped character
[^"'']* # all that is not a double quote or a backslash
)*+
)
"')
| # OR the same with single quotes (and always in capture group 1)
'([^''']*+(?s:''.[^''']*)*+)'')
)
演示