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
Simple Question
Moderator: General Moderators
Code: Select all
$string = "mydomain.com/randomstuff/p1999999";
preg_match("/(\d+)$/", $string, $out);
echo $out[1]."\n";[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:
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;
?>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
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
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
}