Noel Whitemore
Noel Whitemore

Reputation: 794

PHP - What regex code do I need to match this boundary sequence?

I have the following text string:

-asc100-17-asc100-17A-asc100-17BPH-asc100-17ASL

What regex code do I need to extract the values so that they appear in the matches array like this:

-asc100-17

-asc100-17A

-asc100-17BPH

-asc100-17ASL

Thanks in advance!

Upvotes: 0

Views: 50

Answers (4)

Jonny 5
Jonny 5

Reputation: 12389

Might use preg_split with a lookahead as well for your scenario:

print_r(preg_split('/(?=-asc)/', $str, -1, PREG_SPLIT_NO_EMPTY));

Upvotes: 1

aliteralmind
aliteralmind

Reputation: 20163

Based on the very limited information in your question, this works:

-asc100-17[A-Z]*

Regular expression visualization

Debuggex Demo

If you want to capture the post -asc100- code, then use

-asc100-(17[A-Z]*)

Which places 17[the letters] into capture group one.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

You may try this:

$str = "-asc100-17-asc100-17A-asc100-17BPH-asc100-17ASL";
preg_match_all('/-asc\d+-[0-9a-zA-Z]+/', $str, $matches);

// Print Result
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => -asc100-17
            [1] => -asc100-17A
            [2] => -asc100-17BPH
            [3] => -asc100-17ASL
        )
)

Upvotes: 1

effone
effone

Reputation: 2192

Are you trying to break the string in an array? Then why regex is required? This function can handle what you want:

$arr = explode('-asc', '-asc100-17-asc100-17A-asc100-17BPH-asc100-17ASL');
foreach ($arr as $value) {
    if(!empty($value)){
        $final[] = '-asc'.$value;
    }
}
print_r($final);

Output array : Array ( [0] => -asc100-17 [1] => -asc100-17A [2] => -asc100-17BPH [3] => -asc100-17ASL )

Upvotes: 0

Related Questions