tags:

views:

23

answers:

2

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.

Any advice would be much appreciated Thanks!

A: 

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);
?>
Tim C
A: 

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
}
burkestar
This works for what I posted. But how would I accomodate different types of strings like? Coupon Code: SILVER - Use your Gap Silver Card or Gap Silver Visa Card and you'll save with free shipping on your entire order. Enter this code at checkout to see your savings.
allan
basically need to prevent your code from extracting everything and anything after the "SILVER"
allan
This works better "Code: ([a-zA-Z0-9]+)" to support both cases.
burkestar
One last question: How to strip the "Code: XXXX" out of the string and return just the rest of it e.g" "on Red Hot Ruby Jewelry<br><br>" ?
allan