2

I have this link, and i need to work only with the numbers from that link. How would i extract them?

I didn't find any answer that would work with codepcetion.

https://www.my-website.com/de/booking/extras#tab-nav-extras-1426

I tired something like this.

 $I->grabFromCurrentUrl('\d+');

But i won't work.

Any ideas ?

MewTwo
  • 465
  • 4
  • 14

3 Answers3

2

You can use parse_url() to parse entire URL and then extract the part which is most interested for you. After that you can use regex to extract only numbers from the string.

$url = "https://www.my-website.com/de/booking/extras#tab-nav-extras-1426";
$parsedUrl = parse_url($url);

$fragment = $parsedUrl['fragment']; // Contains: tab-nav-extras-1426

$id = preg_replace('/[^0-9]/', '', $fragment);

var_dump($id); // Output: string(4) "1426"
Tomasz
  • 4,847
  • 2
  • 32
  • 41
  • Wow this actually worked. You just saved me a lot of time. Could you maybe explain how this works ? I don't really get $parsedUrl['fragment'] this part. – MewTwo Aug 08 '18 at 08:19
  • @MewTwo you're welcome! If it worked feel free to mark my response as correct one :) – Tomasz Aug 08 '18 at 08:20
  • Also would there be any way ? To make the link dynamic. Since the numbers may change every test. Thats why i tried using the function from codepcetion. If no this will also work fine. – MewTwo Aug 08 '18 at 08:21
  • @MewTwo take a look on documentation of parse_url() it returns you an array with aggregated parts of the url. In your case part which you need is in "fragment" part. – Tomasz Aug 08 '18 at 08:22
  • @MewTwo with php you can get full url like this, for example: https://stackoverflow.com/questions/6768793/get-the-full-url-in-php – Tomasz Aug 08 '18 at 08:24
2

Staying within the framework:

The manual clearly says that:

grabFromCurrentUrl

Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.

Since you didn't used any capturing groups (...), nothing is returned.

Try this:

    $I->grabFromCurrentUrl('~(\d+)$~');

The $ at the end is optional, it just states that the string should end with the pattern.

Also note that the opening and closing pattern delimiters you would normally use (/) are replaced by tilde (~) characters for convenience, since the input string has a great chance to contain multiple forward slashes. Custom pattern delimiters are completely standard in regexp, as @Naktibalda pointed it out in this answer.

Gergely Lukacsy
  • 2,881
  • 2
  • 23
  • 28
0

A variant using preg_match() after parse_url():

$url = "https://www.my-website.com/de/booking/extras#tab-nav-extras-1426";

preg_match('/\d+$/', parse_url($url)['fragment'], $id);

var_dump($id[0]);
// Outputs: string(4) "1426"
AymDev
  • 6,626
  • 4
  • 29
  • 52