Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取文本中与模式匹配的所有字符串_Php_Regex - Fatal编程技术网

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似乎是个打字错误。是的,那是个打字错误,抱歉,编辑过了。