0

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!

2 Answers 2

4

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

$pattern = '!/(.+)/!';
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

I was obviously trying to over complicate things there!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.