Reputation: 4261
I want to find string between first and last underscore (_
) from the below string
I have tried this:
$s = '23_The_Sample_Book_145236985.pdf';
$matches = [];
$t = preg_match('/\_(.*?)\_/', $s, $matches);
print_r($matches[1]);
I want to get output like ...
The_Sample_Book
But i get like...
The
Upvotes: 3
Views: 1427
Reputation: 1584
This should do it, though it does not use regex:
$s = '23_The_Sample_Book_145236985.pdf';
//get the position of the FIRST ocurrence of '_'
$begin = strpos($s, '_') + 1;
//get the position of the LAST ocurrence of '_'
$end = strrpos($s, '_');
//prints what's in between
echo substr($s, $begin, $end - $begin);
Upvotes: 2
Reputation: 20737
This should do it:
<?php
$s = '23_The_Sample_Book_145236985.pdf';
// Separate the string based on underscore and create an array
$arr = explode('_', $s);
// Remove the first and last array elements
// 23 and 145236985.pdf in the case of this string
$arr = array_slice($arr, 1, (count($arr)-2));
// Rejoin with an underscore
echo implode('_', $arr);
Upvotes: 2
Reputation: 1680
hope this helps
$s = '23_The_Sample_Book_145236985.pdf';
$matches = [];
$t = preg_match('/\_(.*)\_/', $s, $matches);
print_r($matches[1]);
Upvotes: 2