user3780692
user3780692

Reputation: 25

Remove "s" on plural word for specific strings using regular expressions?

I have some strings like "3 days ago", "6 hours ago", "9 minutes ago", and "12 seconds ago". I'm new to regular expressions, so I'm not sure how to go about matching the "s" before " ago" so I can strip it out if needed.

Edit: My code in case it can help someone else...

    function timeAgo ($timestamp) {
        $difference = time() - strtotime($timestamp);
        if ($difference > (60*60*24)) {
            $difference = round($difference/60/60/24) . " days ago";
        }
        else if ($difference > (60*60)) {
            $difference = round($difference/60/60) . " hours ago";
        }
        else if ($difference > 60) {
            $difference = round($difference/60) . " minutes ago";
        }
        else if ($difference > 0) {
            $difference = $difference . " seconds ago";
        }
        $int = filter_var($difference, FILTER_SANITIZE_NUMBER_INT);
        if ($int == 1) {
            $difference = preg_replace('/.(?= ago)/', '', $difference);
        }
        return $difference;
    }

Upvotes: 0

Views: 586

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174826

Try the below regex to match s which was just before to <space>ago,

.(?= ago)

DEMO

Upvotes: 1

Related Questions