我有这两个链接:
http://www.something.com/something/edit/id/$id/type/$type
和
http://www.something.com/something/edit/id/:id/type/:type/collection/:collection
因为,我不熟悉PHP的RegEx,我想从这两个链接中提取这个:
// first link
array(
'id', 'type',
);
// second link
array('id', 'type', 'collection');
是否可以使用PHP的RegEx解析并提取字符串的$id
和:type
部分?
谢谢大家的帮助!
修改
对于所有下来的选民,请注意我要从$
或:
开始,以/
或空字符串结尾提取所有这些项目,然后推送那些以那种格式匹配的新数组。
答案 0 :(得分:2)
您可以将正则表达式与look behind assertion:
一起使用$link = 'http://www.something.com/something/edit/id/$id/type/$type';
// or
$link = 'http://www.something.com/something/edit/id/:id/type/:type/collection/:collection';
preg_match_all('~(?<=[:$])[^/]+~', $link, $matches);
var_dump($matches);
说明:
~ Pattern delimiter
(?<=[:$]) Lookbehind assertion. Matches : or $
[^/]+ Any character except of / - multiple times
~ Pattern delimiter
答案 1 :(得分:1)
首先删除链接中不必要的部分
$string = str_replace('http://www.something.com/something/edit/', '', $url);
比explode
其余的字符串
$string = rtrim($string, '/');
$array = explode('/', $string);
$values = [];
$keys = [];
foreach ($array as $i => $param) {
if ($i % 2 == 0) {
$keys[] = $param;
} else {
$values[] = $param;
}
}
$returnArray = array_combine($keys, $values);
答案 2 :(得分:1)
我想你想要这样的东西,
(?<=\/id\/)[^\/]+|\/type\/\K[^\/]*|collection\/\K[^\/\n]*
代码:
<?php
$string = <<<EOD
http://www.something.com/something/edit/id/\$id/type/\$type
http://www.something.com/something/edit/id/:id/type/:type/collection/:collection
EOD;
preg_match_all('~(?<=\/id\/)[^\/\n]+|\/type\/\K[^\/\n]*|collection\/\K[^\/\n]*~', $string, $matches);
var_dump($matches);
?>
<强>输出:强>
array(1) {
[0]=>
array(5) {
[0]=>
string(3) "$id"
[1]=>
string(5) "$type"
[2]=>
string(3) ":id"
[3]=>
string(5) ":type"
[4]=>
string(11) ":collection"
}
}