Lee Armstrong
Lee Armstrong

Reputation: 11452

PHP Regex Match Text Between quotes

I have the following text....

B/H888/QG and I would like to extract the H888 from this. There will always be two forwards slashes encapsulating this.

$subject = "B/H888/QG";
$pattern = '/(.+)/';
preg_match($pattern, $subject, $matches);
print_r($matches);

The best I can get to is the above however this is completely wrong and outputs

H888/QG!

Upvotes: 0

Views: 672

Answers (2)

deceze
deceze

Reputation: 522109

You need to delimit the regex pattern, in this case the / are taken as the delimiters. Use something else:

$pattern = '!/(.+)/!';

Upvotes: 4

nickb
nickb

Reputation: 59699

Why use a regex? Just use explode.

$subject = "B/H888/QG";
$pieces = explode( '/', $subject);
echo $pieces[1]; // Outputs H888

Demo

If you must use a regex, you need something like this:

$subject = "B/H888/QG";
$pattern = '/\/([\w\d]+)\//';
preg_match($pattern, $subject, $matches);
echo $matches[1]; // Outputs H888

Demo

Upvotes: 3

Related Questions