Jake
Jake

Reputation: 3486

How to use regex in PHP to get int after slash in string

I've tried to create a code in PHP that gets the topic id after the forward slash in a given string. However the problem i'm having is that its returning nothing, how can i make it return the int?

echo  preg_match('/([^/]+)/', 'Learning-English/478', $discussion_id);
echo $discussion_id;

This is for an online forum, thank you for your help; it's much appreciated. If you need ay more information please don't hesitate to leave a comment.

Upvotes: 1

Views: 908

Answers (2)

ITroubs
ITroubs

Reputation: 11215

you could just use explode() like this:

$arr = explode('/',$string);
$discussion_id = $arr[count($arr)-1];

this will split your string and then get you the last part.

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80649

preg_match("#/(\d+)$#", 'Learning-English/478', $discussion_id);

That would work for you.

To print the id(matched number); you need to echo $discussion_id[1].

Here is a working link.


For the newer strings, you wouldn't be needing the string end match($). Thus, the regex will be:

preg_match("#/(\d+)#", 'Looking-for-Pen-Pals/1161&t=viewDiscussion', $discussion_id);
echo $discussion_id[1];

Upvotes: 2

Related Questions