简体   繁体   中英

Extract only numbers from link with codeception

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 ?

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"

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 .

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM