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.

0

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
basically need to prevent your code from extracting everything and anything after the "SILVER"
This works better "Code: ([a-zA-Z0-9]+)" to support both cases.
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>" ?
1
if (preg_match('/(?<=: ).+(?=<)/', $subject, $regs)) {
    // ow right! match!
    $result = $regs[0];
} else {
    // my bad... no match...
}

Comments

0

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);
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.