Page 1 of 1

Remove everything after first occurence

Posted: Fri May 14, 2010 5:39 pm
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 -

Re: Remove everything after first occurence

Posted: Fri May 14, 2010 6:12 pm
by thiscatis
got it

Code: Select all

function getIdFromUrl($page_action) {
  preg_match('/^[^-]+/', $page_action, $match);
  return $match[0];
}
did the trick

Re: Remove everything after first occurence

Posted: Sun May 16, 2010 12:53 am
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/