six7zero9
six7zero9

Reputation: 323

Make two simple regex's into one

I am trying to make a regex that will look behind .txt and then behind the "-" and get the first digit .... in the example, it would be a 1.

$record_pattern = '/.txt.+/';
preg_match($record_pattern, $decklist, $record);
print_r($record);

.txt?n=chihoi%20%283-1%29

I want to write this as one expression but can only seem to do it as two. This is the first time working with regex's.

Upvotes: 1

Views: 45

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

Your regex would be,

\.txt[^-]*-\K\d

You don't need for any groups. It just matches from the .txt and upto the literal -. Because of \K in our regex, it discards the previously matched characters. In our case it discards .txt?n=chihoi%20%283- string. Then it starts matching again the first digit which was just after to -

DEMO

Your PHP code would be,

<?php
$mystring = ".txt?n=chihoi%20%283-1%29";
$regex = '~\.txt[^-]*-\K\d~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    }
?> //=> 1

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

You can use this:

$record_pattern = '/\.txt.+-(\d)/';

Now, the first group contains what you want.

Upvotes: 2

Related Questions