Php 获取文本中与模式匹配的所有字符串
我试图从文本中获取Php 获取文本中与模式匹配的所有字符串,php,regex,Php,Regex,我试图从文本中获取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和
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
你也可以考虑。
你需要对每个./p>使用单独的正则表达式。(?<=t\(").*?(?="\))|(?<=t\(\').*?(?='\))
\K
在期末打印时放弃先前匹配的字符。您需要为每个字符使用单独的正则表达式
(?<=t\(").*?(?="\))|(?<=t\(\').*?(?='\))
\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:\\.[^'\\]*)*+)'\)
)
使用此模式,只需几个步骤即可完成:
$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:\\.[^'\\]*)*+)'\)
)
是“和
”
还是“”
和”)
?@JESUISCHARLIE似乎是个打字错误。是的,那是个打字错误,抱歉,编辑过。是“和”
还是”
)?@JESUISCHARLIE似乎是个打字错误。是的,那是个打字错误,抱歉,编辑过了。