BottyZ BottyZ - 3 years ago 149
PHP Question

Using preg_match to extract string into array between : & | characters

I'm trying to extract serial numbers from a string to compare for matches and thought it might be possible with preg_match, but I'm struggling with the regex.

Can anyone offer any assistance please?

Current attempt is as follows:

$example = "CPM-200:0123456L|CPM-100:9876543L|CJ Pro:CJP33-011";

pre_match("/\:(.*?)\|/", $example, $matches);

Currently the above spits out:

Array(2) {
[0]=> string(10) ":0123456L|"
[1]=> string(8) "0123456L"

But I actually want to have it extract to:

Array(0) {
[0] => 0123456L
[1] => 9876543L
[2] => CJP33-011

I've never been great with the regex! I've tried various combinations and the above is the closest I've managed to get to. Need to find a decent online tutorial.

Answer Source

You can use this


Regex Demo

Regex Breakdown

: #Match :
([^|]+) #Match anything other than |
  \| #Match | literally
    | #Alternation(OR) --> Match | or $
   $ #End of string

PHP Code

$re = "/:([^|]+)(?:\\||$)/"; 
$str = "CPM-200:0123456L|CPM-100:9876543L|CJ Pro:CJP33-011"; 

preg_match_all($re, $str, $matches);

Ideone Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download