Remove everything after first occurence

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Remove everything after first occurence

Post by thiscatis »

Hi phpdn,

I'm fetching a clean url from my application which all look like:

Code: Select all

http://domain.com/this-page/[id]-this-is-a-clean-url/
Where id is an integer.
I only want that id

In php the code will look like:

Code: Select all

//...stuff happens before this
// clean up url, prevent malicious code
$page_action = preg_replace('/[^a-zA-Z0-9-_\_]/', '', $_GET['action']); 
// now $page_action == [id]-this-is-a-clean-url
// and I only want the [id] part, which is always an integer
What should I do to go from the $page_action to get only the [id], which is actually everything before the first occurence of -.
So delete everything after the first occurence of -
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Re: Remove everything after first occurence

Post by thiscatis »

got it

Code: Select all

function getIdFromUrl($page_action) {
  preg_match('/^[^-]+/', $page_action, $match);
  return $match[0];
}
did the trick
jimmy patel
Forum Newbie
Posts: 3
Joined: Sun May 16, 2010 12:14 am

Re: Remove everything after first occurence

Post by jimmy patel »

This will help you to find out Id from current url:

Code: Select all

preg_match(~.*/(\d+)-.*/~m, $string)

MoonRose Infotech
W: http://www.moonroseinfotech.com/
Post Reply