David
David

Reputation: 326

Get information between two strings

I have the following PHP string

$string = "Hello World<br>- 8/7/2013<br>Hello World";

So basically, I need to get the information between a dash and space (-) and the closest line break tag. Your help is very much appreciated! I looked for hours but haven't been successful. I don't think that preg_replace would help either.

Upvotes: 0

Views: 72

Answers (3)

Logan Murphy
Logan Murphy

Reputation: 6230

Try this

function getData($haystack) {
    $dash = strpos($haystack, "- ") + 2;
    $br = strpos($haystack, "<br>", $dash);
    return substr($haystack, $dash, $br - $dash);
}

Upvotes: 0

pajaja
pajaja

Reputation: 2202

You can use preg_match:

if(preg_match("~-\s(.*?)<br>~", $string, $matches)) {
    $data = $matches[1];
}

Upvotes: 1

Ry-
Ry-

Reputation: 224962

strpos finds the index of a substring (optionally after a specified index), so:

$start = strpos($string, '- ') + 2;
$end   = strpos($string, '<br>', $start);
$part  = substr($string, $start, $end - $start);

Ta-da!

Upvotes: 3

Related Questions