使用php和preg_match在文本文件中选择带有.domain的单词


Select words with .domain in textfile with php and preg_match

我试着选择一些以.domain

结尾的名字

文件文本如下:

.
..
script
truc.domain
machin.domain

例如,我想选择truc。domain and machine .domain

I try this

if (preg_match('~$.domain~', $result)){
    echo $result;
}

if (preg_match('/$.domain/', $result)){
    echo $result;
}

但是它不工作…

我的第二个问题是,在许多例子中,我看到preg_match与preg_match('/filter/)preg_match('~filter~')

之间的区别是什么/ ~ ?

/~之间无差异。您可以从广泛的分隔符中进行选择。这个想法是,你可以选择一个不属于你的模式的字符,所以你不必逃避任何东西。例如,如果您想匹配3/4并使用/作为分隔符,则必须写/3'/4/,但使用~可以写~3/4~

关于你的问题,你必须把锚放在它应该匹配的位置。因为它是字符串结束锚,所以它在末尾。您还可能希望转义.或将其放在字符类中。否则它将匹配任何字符:

/[.]domain$/

注意,您的匹配将只包含.domain。如果您希望以.domain结尾的整个"name",则需要将其包含在模式中。我不知道你定义的名字是什么,但是如果我们使用"字母数字和下划线",这是一个单词字符的regex定义,你可以简单地在'w+前添加尽可能多的"单词"在.domain前面。

最后,由于您似乎想要找到这个的多个实例,并且在行结尾,而不是字符串结尾,您需要使用preg_match_allm修饰符,这使得$也匹配行结尾:

if(preg_match_all('/'w+[.]domain$/m', $input, $matches))
{
    print_r($matches[0]);
}

打印

Array
(
    [0] => truc.domain
    [1] => machin.domain
)

工作演示。

要获得句号前面的部分,您可以在.explode()这些结果,或者您可以捕获名称:

if(preg_match_all('/('w+)[.]domain$/m', $input, $matches))
{
    print_r($matches[0]);
    print_r($matches[1]);
}

将打印

Array
(
    [0] => truc.domain
    [1] => machin.domain
)
Array
(
    [0] => truc
    [1] => machin
)
工作演示。

~/都是允许的regex分隔符,您可以使用大约。

.表示任何字符,为了匹配点,您需要转义它

$意味着行结束,所以你的正则表达式应该看起来像:

/'.domain$/

您的正则表达式没有正确构建,如果您想返回匹配的文本,您必须为preg_match函数提供第三个参数。

如果你想匹配行尾,你的正则表达式必须像这样:

 if (preg_match('/(.*)'.domain$/', $search_text, $result)){
     echo $result[0]; //Note this is an array, that matches all the pattern
     echo $result[1]; // This is the match of the first subgroup
 }