<分区>
我需要使用 preg_match 来获取符合特定条件的文件。例如,我想找到一个名为“123-stack-overflow.txt”的文件。 123- 之后和 .txt 之前可以有任何字符。
如何修改它才能正常工作?
preg_match("/^$ID-(.+).txt/" , $name, $file);
标签 php regex preg-match
<分区>
我需要使用 preg_match 来获取符合特定条件的文件。例如,我想找到一个名为“123-stack-overflow.txt”的文件。 123- 之后和 .txt 之前可以有任何字符。
如何修改它才能正常工作?
preg_match("/^$ID-(.+).txt/" , $name, $file);
最佳答案
正则表达式 ^123-.+\.txt$
^ # Match start of string
123- # Match the literal string 123-
(.+) # Match anything after (captured)
\.txt # Match the literal string .txt
$ # Match end of string
PHP:
$str="123-stack-overflow.txt";
preg_match('/^123-(.+)\.txt$/',$str,$match);
echo $match[0];
echo $match[1];
>>> 123-stack-overflow.txt
>>> stack-overflow
关于php - preg_match 获取包含 123 和 .txt 之间任何字符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13769287/