Simple Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Simple Question

Post by mjseaden »

Dear All

I have a string, in the form

mydomain.com/randomstuff/pX

where X is a number (can be more than 1 digit).

I simply want to extract this number from the end of the URL so I have X in a separate variable.

What PHP string function do I use to do this?

Many thanks

Mark
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Code: Select all

$string = "mydomain.com/randomstuff/p1999999";
preg_match("/(\d+)$/", $string, $out);
echo $out[1]."\n";
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

[php_man]strpos[/php_man] and [php_man]substr[/php_man] are what you are looking for (with a little help from [php_man]strlen[/php_man]).

In your case:

Code: Select all

<?php

$PATH = "mydomain.com/randomstuff/p7373434349";

echo $PATH."\n";
$ppos = 1 + strpos($PATH, "p");
$len = strlen($PATH) - $ppos;
$dir = substr($PATH, $ppos, $len);
echo $dir;

?>
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

Thanks Weirdan

I'm going to have to clarify the query, I've just realised.

Sometimes I might have a /pX after the rest of the URL, but sometimes just a number. If it's just a number (e.g. just /X, not /pX) I need it to go one of two ways depending on whether it's X or pX. How do I detect for each case? Obviously if it is pX I would use the code you gave.

Many thanks

Mark
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Code: Select all

$string = "mydomain.com/randomstuff/p1999999";
preg_match("/(p?)(\d+)$/", $string, $out);
$is_p = !empty($out[1]);
$digits = $out[2];
if($is_p) {
    // do something
} else {
    // do something else
}
Post Reply