帮助 PHP 正则表达式提取字符串周围的文本


help with a PHP regex to extract text around a string

我正在尝试使用正则表达式,它只是打破了我的大脑。 我会认为我有它,脚本就坏了。我需要尝试为人们提供一种通过短信报告其位置的方法。我要求他们给我发短信,看起来像这样:

我放弃了,停下来过夜。 在主街和松树找到我, 佐治亚州亚特兰大。

我想在Find me at打破它.我需要捕获右侧的所有内容(主要是他们的街角),我需要能够检测他们是否没有对Find使用正确的大写字母。

有什么建议吗?

preg_match("/[Ff]ind me at (.+)/", "I give up, find me at street 1 and street 2")将捕获"Find Me at"之后的所有内容

以下正则表达式将为您工作:

Find me at (.*)$

如果希望它忽略大小写,可以使用"忽略大小写"选项指定它(?i:)

试一试:/find me at (.*)$/i

嗯,我想到了一个非正则表达式解决方案。

$string = 'I give up, stopping for the night. Find me at Main Street and Pine, Atlanta, GA.';
$findMe = 'Find me at';
$address = substr(strstr($string, $findMe), strlen($findMe));
if ($address == '') {
    // no match
}

然后是一个基于正则表达式的解决方案。

preg_match('/Find me at (.*)$/', $string, $match);
if (!isset($match[1])) {
    // no match found
} else {
    $address = $match[1];
}

我只会preg_split()。如果你知道你想要什么,应该永远在最后。

$str = "I give up, stopping for the night. Find me at Main Street and Pine, Atlanta, GA."
$strSplit = preg_split("/Find me at /i", $str);
$whatYouWant = $strSplit[1];