-4

I'm trying to assign it to a variable in PHP, but all the Regex and preg_replace I've tried doesn't help me. Here is a sample text.

Claim Code:
7241B-2HWRXR9-2P2BA
$1.00

I want to pull out exactly what is in the middle, which is 7241B-2HWRXR9-2P2BA.

Madan Sapkota
  • 25,047
  • 11
  • 113
  • 117
thevoipman
  • 1,773
  • 2
  • 17
  • 44
  • Idk man, it looks good to me? I didn't try it though but sure would have liked some reasoning for a downvote – Xander Luciano Apr 26 '15 at 05:45
  • possible duplicate of [get number in front of 'underscore' with php](http://stackoverflow.com/questions/2220998/get-number-in-front-of-underscore-with-php) – a coder Apr 26 '15 at 06:49

3 Answers3

1

You can use the following to match:

Claim Code:\s*([\w-]+)\s*\$(\d+(?:\.\d+)?)

And you can pull out whatt you want by $1

See DEMO

karthik manchala
  • 13,492
  • 1
  • 31
  • 55
1

Less elegant than a regexp / preg_replace, but this should work, too: Put the string into an array, then only use line 2 (array element number 1).

<?php
$string = 'Claim Code: ...............';
$lines = explode("\n", $string); //Transform the string into an array, separated by new lines (\n) (each index in the array is a single line from the string
echo $lines[1]; //this is 2nd line of the string, i.e. the claim code
nicolaus-hee
  • 787
  • 1
  • 9
  • 25
1

If the code has always the same format (5-7-5 chars), you can use:

$str = 'Claim Code:
7241B-2HWRXR9-2P2BA
    $1.00';

preg_match('~[\w]{5}\-[\w]{7}\-[\w]{5}~', $str, $matches);
echo $matches[0]; // returns 7241B-2HWRXR9-2P2BA

UPDATE
For optional code length this regex is possible:

preg_match('~.*:\s+([\w\-]{10,25})\s+.*~', $str, $matches);
echo $matches[1]; //       ^^ here set the min and max code length, or remove it 

// without setting min/max code length:
preg_match('~.*:\s+([\w\-]+)\s+.*~', $str, $matches);
pavel
  • 26,538
  • 10
  • 45
  • 61