112233
112233

Reputation: 2466

Unable to extract value between two characters

I'm trying with so many examples online to get the numbers between a _ and .. It simple outputs empty string for whatever reason.

String:

/chat_3.txt

I want to be able to extract the number in it, which is 3 in the above string.How do I do that?

I tried as below, but it gives empty output:

$s = '/chat_3.txt';
$matches = array();
$t = preg_match('/_(.*?)\./s', $s, $matches);

Then, I write the output into a file in Joomla like this:

$file = __DIR__ . '/file.txt';
JFile::write($file, $matches[1]);

EDIT:

In fact, I passed array instead of string.

Upvotes: 0

Views: 39

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

So, the real issue is that

I passed array instead of string

If you need to extract the digits from the last occurrence of .+digits+., you can easily achieve that with a preg_filter function:

$s = array('/chat_3.txt', '/chat_old.txt', '/chat_15.txt');
$matches = array();
$t = preg_filter('/.*_(\d+)\..*/s', '$1',$s);
print_r($t);

See the PHP demo

The preg_filter will return only those values where it found a match. The replaced values will be returned. So, .*_(\d+)\..* will match any 0+ chars as many as possible up to the last _ + 1 or more digits (captured into Group 1) + . + any zero or more chars up to the end of string, and will replace all this with the digits found in Group 1.

Upvotes: 1

Related Questions