使用Regex在给定单词之前搜索单词


Using Regex to search for a word before a given word

我正在慢慢拼凑class.iCalReader.php的一个实现,以获取iCal提要并生成一个表,其中包含某一天建筑中发生的所有事件。作为其中的一部分,我需要提取事件将在哪个房间中——这包含在iCal数组的"描述"字段中。

因此,我已经确定我需要使用regex在描述中查找单词"room",然后返回单词"room-"之前的单词。然而,真正的正则表达式让我难以捉摸——我不是一个优秀的程序员。

目前我有:

function getRoom($description, $search = 'Room')
{
if (1 !== preg_match('#'s('w+)'s+('.$search.')'s#i', $description, $matches)) return 'TBA';
return $matches[1];
}

在函数调用中,我将变量$search设置为"Room"。可以有多个房间。

作为事件数组的一部分,.ical流包含以下内容:

DESCRIPTION:Event Type: Private'n'nRegistrations: 1 'n'nResources: Indian Room

然后,一旦class.iCalReader.php使用以下行解析它,我就会得到这个:

$description = $event['DESCRIPTION'];

稍后在我的php中,我将$room设置为:

$room = getRoom($description);

然后,我尝试使用返回值

if ($room !== FALSE) {
    echo "<td>". stripslashes($room) ."</td>";
} else {
    echo "<td>No Room Allocated</td>";
}

关于我哪里出了问题,有什么建议吗?

请检查:http://regex101.com/r/jJ5mU7/3

您可能需要删除第一个#,或者它是php特定的吗?

你需要向前看?=

你需要非贪婪的匹配部分(有2个房间):+后的一个问号

更改为

if (1 !== preg_match(''s('w+)'s+?(?='.$search.')'s', $description, $matches)) return 'TBA';

专注于?和?=

试试这个:

'#'s('w+)'s+('.$search.')'s#s'

'#''s(''w+)''s+('.$search.')''s#是'

if ( preg_match('#'s('w+)'s+('.$search.')'s#s', $description, $matches))
  return $matches[1];
else 
  return 'TBA';

在您的帮助下,我已经成功地对它进行了排序!它没有正确处理描述,然而,这已经成功了:

    function getRoom($description, $search = 'Room')
{
    $description .= ' ';
    if (1 !== preg_match('#'s(('w+)'s+Room)['s.;]#i', $description, $matches)) return 'TBA';
    return $matches[1];
}

谢谢大家!