如何解析并将部分字符串放入数组中?
我有一个像这两个环节:如何解析并将部分字符串放入数组中?
http://www.something.com/something/edit/id/$id/type/$type
而且
http://www.something.com/something/edit/id/:id/type/:type/collection/:collection
,因为我不擅长PHP的正则表达式,我想从这两个环节提取此:
// first link
array(
'id', 'type',
);
// second link
array('id', 'type', 'collection');
是否可以使用PHP的RegEx解析和提取这些$id
和:type
部分字符串?
谢谢大家的帮助!
编辑:
为了你下的选民,请已了解,我想提取所有这些项目开始$
或:
并与/
或空字符串结束,并推那些以这种格式匹配到一个新的数组。
您可以使用正则表达式与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
我要接受这个答案。谢谢你! – zlomerovic 2014-09-04 11:51:16
好的。你可能完全用你的问题来回答。如果任何人立即清楚地了解问题,它可能会得到提升。当人们阅读“url,parse,variables,PHP”这些短语时,他们可能倾向于说这个*已经被回答了,但是我认为你所做的最后是一些特别的东西。 – hek2mgl 2014-09-04 11:55:16
'我想从$或:开始提取所有这些项目。我认为这两个字符不会显示在最终输出中。 – 2014-09-04 11:57:08
先删除
$string = str_replace('http://www.something.com/something/edit/', '', $url);
的任何不必要的部分比explode
休息串
不错,但@ hek2mgl的例子更好。谢谢你。 – zlomerovic 2014-09-04 11:51:01
我想你想这样的事情,
(?<=\/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"
}
}
您可能不想为此使用正则表达式。 – 2014-09-04 11:41:24
我想将所有以'$'或':'开始并以'/'或空字符串结尾的部分抽取到数组中。 – zlomerovic 2014-09-04 11:41:59
@ TheParamagneticCroissant - 那该怎么做呢? – zlomerovic 2014-09-04 11:44:08