Jump to content

get text after certain string until a new line


dadamssg

Recommended Posts

I have this function to search for a 'word'(string with white spaces around it) after a specified string and it works great. I need to modify it to where it looks for all characters after the specified string until it hits a new line.

 

The following returns "07/23/2012". But i would like to do is modify it so if i input "Property: " into the preg_match function it returns "The best resort in town". I suck at regex though. Any help would be much appreciated. thanks!

 

$body = "Dear John Doe, your information is below
        Property: The best resort in town
Check in date: 07/23/2012
Check out date: 07/26/2012

Alternate Check in date: 07/27/2012
Alternate Check out date: 07/29/2012";

if(preg_match('/(?<=Check in date: )\S+/i', $body, $match))
{
echo $match[0];
}

#property: [^\r\n]+#i

 

Options: case insensitive

 

Match the characters ?property: ? literally ?property: ?

Match the regular expression below and capture its match into backreference number 1 ?([^\r\n]+)?

  Match a single character NOT present in the list below ?[^\r\n]+?

      Between one and unlimited times, as many times as possible, giving back as needed (greedy) ?+?

      A carriage return character ?\r?

      A line feed character ?\n?

thanks for the that, xyph. I did the following but it is returning "Property: " with it. Anyway to cut that out?

 

	$body = "Dear John Doe, your information is below
Check in date: 07/23/2012
Check out date: 07/26/2012
Property: The best inn around \n

Alternate Check in date: 07/27/2012
Alternate Check out date: 07/29/2012";

echo "$body<br/><br/>";

if(preg_match('/(?<=Check in date: )\S+/i', $body, $match))
{
echo $match[0]."<br/><br/>"; //returns  '07/23/2012'
}

if(preg_match('#Property: [^\r\n]+#i', $body, $match))
{
echo $match[0]; //returns 'Property: The best inn around'
}

awesome. thanks. Here's my function

 

function get_phrase_after_string($haystack,$needle)
{
	//length of needle
	$len = strlen($needle);

	//matches $needle until hits a \n or \r
	if(preg_match("#$needle([^\r\n]+)#i", $haystack, $match))
	{
		//length of matched text
		$rsp = strlen($match[0]);

		//determine what to remove
		$back = $rsp - $len;

		return trim(substr($match[0],- $back));
	}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.