简体   繁体   中英

Using Regex to search for a word before a given word

I am slowly piecing together an implementation of class.iCalReader.php, to take an iCal feed and produce a table with all the events that are going on in a building on a particular day. As part of that, I need to extract which room the events are going to be in - this is contained within the 'Description' field of the iCal array.

So, I've established I need to use regex to look in description for the word 'room', and then return the word before 'room'. However, the actual regex eludes me - I'm not a great programmer.

Currently I have:

function getRoom($description, $search = 'Room')
{

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

}

where I set the variable $search to 'Room' in the call to the function. There can be more than one room.

The .ical stream contains, as part of its' array of events, the following:

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

I then get this once it's been parsed by class.iCalReader.php using this line:

$description = $event['DESCRIPTION'];

Later on in my php, I set $room as so:

$room = getRoom($description);

Then, I try and return the value using:

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

Any suggestions as to where I'm going wrong?

Please check: http://regex101.com/r/jJ5mU7/3

You may need to remove the first # or is it something php specific?

You need lookahead with ?=

You need non-greedy matching part (with 2 rooms): a question mark after the +

Change to

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

with a focus on the ? and the ?=

Try this:

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

or

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

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

I've managed to sort it, with your help! It wasn't processing the description properly, however, this has done the trick:

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

Thanks guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM