获取第一个和最后一个空格字符之间的字符串

时间:2016-02-29 13:27:04

标签: php regex

我想在下面的字符串中找到第一个和最后一个下划线(_之间的字符串

我试过这个:

$s = '23_The_Sample_Book_145236985.pdf';
$matches = [];
$t = preg_match('/\_(.*?)\_/', $s, $matches);
print_r($matches[1]);

我希望输出像......

The_Sample_Book

但我觉得......

The

3 个答案:

答案 0 :(得分:2)

希望这会有所帮助

    $s = '23_The_Sample_Book_145236985.pdf';
    $matches = [];
    $t = preg_match('/\_(.*)\_/', $s, $matches);
    print_r($matches[1]);

检查截图 enter image description here

答案 1 :(得分:2)

这应该这样做:

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

答案 2 :(得分:2)

这应该这样做,虽然它不使用正则表达式:

$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);