[英]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. 我没有找到适用于Codepcetion的答案。
https://www.my-website.com/de/booking/extras#tab-nav-extras-1426 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. 您可以使用parse_url()解析整个URL,然后提取最感兴趣的部分。 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
grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group .
针对当前URI执行给定的正则表达式,并返回第一个捕获组 。 If no parameters are provided, the full URI is returned.
如果未提供任何参数,则返回完整的URI。
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 . 自定义模式定界符在regexp中是完全标准的,正如@Naktibalda在此答案中指出的那样。
A variant using preg_match()
after parse_url()
: 在
parse_url()
之后使用preg_match()
变体:
$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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.