如何使用| preg_match中的运算符用于在字符串之间进行搜索?

时间:2016-12-14 06:11:46

标签: php regex preg-match

我已经看过很多答案,但似乎没有人帮我解决我的情况。我需要从本文中提取评论:

Comments: These are the comments and they end at this full stop. Remember, you can only use the personal information...

或者这个文字:

Comments: These are the comments and they end at this full stop. You can only use the personal information...

这里有一个工作示例:https://regex101.com/r/apIT0O/1

但我似乎无法将其纳入PHP。我可以得到一个与之合作:

$pattern = "/(?<=Comments: )(.*?)(?= Remember, you can)/s";

但是这有什么问题?

$pattern = "/(?<=Comments: )(.*?)(?= Remember, you can)|(?<=Comments: )(.*?)(?= You can)/s";

非常感谢!

2 个答案:

答案 0 :(得分:0)

使用preg_match_all,您可以使用正则表达式获得所有结果。

试试这个:

/(?<=Comments: )(.*?)(?= Remember, you can)|(?<=Comments: )(.*?)(?= You can)/s

Explanation

示例代码:

<?php

$re = '/(?<=Comments: )(.*?).(?= Remember, you can)|(?<=Comments: )(.*?)(?= You can)/sm';
$str = 'Comments: These are the comments and they end at this full stop. Remember, you can only use the personal information...

Comments: These are the comments and they end at this full stop. You can only use the personal information...';
preg_match_all($re, $str, $matches);
print_r($matches);
?>

Runt it here

答案 1 :(得分:0)

你也可以通过这样的preg_match获得你想要的价值。这是代码

<?php
$data="Comments: These are the comments and they end at this full stop. Remember, you can only use the personal information...";
preg_match("/(.*)(?<=Comments:)(.*?)(?= Remember, you can)(.*)/",$data,$m);
echo $m[2];
?>

<强>输出:

这些是评论,它们在这句话结束。

或者您可以使用

print_r($ m)它将打印您使用正则表达式捕获的所有值。 希望它可以帮到你。