allan
allan

Reputation: 21

Get characters between two strings in a larger string

I would like to be be able to use a regular expression in PHP to be able to extract the value of "Ruby9" from the following html snippet

on Red Hot Ruby Jewelry<br>Code: Ruby9<br>

Sometimes the "Code" will be alphanumeric,numeric, or just letters.

Upvotes: 2

Views: 103

Answers (3)

marverix
marverix

Reputation: 7705

if (preg_match('/(?<=: ).+(?=<)/', $subject, $regs)) {
    // ow right! match!
    $result = $regs[0];
} else {
    // my bad... no match...
}

Upvotes: 1

burkestar
burkestar

Reputation: 777

Try this regex:

$str = "on Red Hot Ruby Jewelry<br>Code: Ruby9<br>";

$pattern  = "/Code: ([^<]+)/"; // matches anything up to first '<'
if(preg_match($pattern, $str, $matches)) {
    $code = $matches[1]; // matches[0] is full string, matches[1] is parenthesized match
} else {
    // failed to match code
}

Upvotes: 1

Tim C
Tim C

Reputation: 1934

If the pattern is always the same the regular expression would be like this:

"<br>Code: ([a-zA-Z0-9]+)<br>"

That will capture any alpha or alphanumeric or just numeric string following a
Code: and before a
. Try the following:

<?php
$subject = "on Red Hot Ruby Jewelry<br>Code: Ruby9<br>";
$pattern = '<br>Code: ([a-zA-Z0-9]+)<br>';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

Upvotes: 0

Related Questions