kalaba2003
kalaba2003

Reputation: 1229

Checks if a string ends with a specific word in php?

There are many questions like this question but I can not find exact answer. And I am unfamiliar Regular Expresion topic.

I wanted to know if $variable ends with "books".

For example :

$variable = "some-historical-books". 

So, I will display books page if it ends with books.

Thank you.

Upvotes: 4

Views: 13358

Answers (3)

David Müller
David Müller

Reputation: 5351

You don't definiteley need regex here:

<?php
$variable = "some-historical-books";
$searchterm = "books";

$pos = strrpos($variable, $searchterm);

if ($pos !== false && strlen($searchterm) + $pos == strlen($variable))
    echo "yep, it's at the end";

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44289

Maybe you should look into a tutorial. What you are looking for is an anchor, that marks the end of the string.

if(preg_match('/books$/', $variable))
    // redirect to books page

Upvotes: 17

Ibu
Ibu

Reputation: 43850

All you need to do is to add the word you need and a $ at the end of your regex

$pattern = "/books$/";

Just like if you want to find out if your value starts with a specific string, you can use ^ at the beginning :

$pattern = "/^Books/";

Upvotes: 6

Related Questions