Staple
Staple

Reputation: 712

Getting a number when it has certain prefix from a block of text in PHP

I have a big paragraph and at a random point in it a string like this occurs which I'd like to extract:

PID: 45678437

There is a space before 'PID' and after the number, the number can be 6-10 characters in length.

I actually only need the number but would like to check it is preceded with PID: as there may be other large numbers in the paragraph.

:)

Upvotes: 0

Views: 2444

Answers (3)

Jason McCreary
Jason McCreary

Reputation: 73011

/ PID: (\d{6,10})/

This will match a space followed by PID: followed by a space followed by 6-10 digits and capture the digits.

I would encourage you to learn Regular Expressions. They are a powerful tool.

Upvotes: 2

Alejandro Iván
Alejandro Iván

Reputation: 4061

<?php
    $string = "PID: 4567895";
    preg_match("/PID:\s(\d{6,10})/", $string, $result);
    $value = $result[0];
    echo "The value is: {$value}";
?>

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

try this:

$pattern = '~(?<=\sPID:\s)[0-9]{6,10}(?=\s)~';
preg_match($pattern, $text, $match);
echo $match[0];

The idea is to use lookaround to only checks characters before and after the number without matching them.

Upvotes: 0

Related Questions