我有一个类似这样的字符串:
traceroute <ip-address|dns-name> [ttl <ttl>] [wait <milli-seconds>] [no-dns] [source <ip-address>] [tos <type-of-service>] {router <router-instance>] | all}我想创建一个这样的数组:
$params = array(
<ip-address|dns-name>
[ttl <ttl>]
[wait <milli-seconds]
[no-dns]
[source <ip-address>]
[tos <tos>]
{router <router-instance>] | all}
);我应该使用preg_split('/someregex/', $mystring)吗?或者还有更好的解决方案吗?
发布于 2012-01-27 19:46:12
您可以使用preg_match_all,例如:
preg_match_all("/\\[[^]]*]|<[^>]*>|{[^}]*}/", $str, $matches);并从$matches数组中获得结果。
发布于 2012-01-27 20:54:15
使用负环视。这个函数对<使用了负向先行。这意味着如果它在空格前面找到一个<,它将不会被拆分。
$regex='/\s(?!<)/';
$mystring='traceroute <192.168.1.1> [ttl <120>] [wait <1500>] [no-dns] [source <192.168.1.11>] [tos <service>] {router <instance>] | all}';
$array=array();
$array = preg_split($regex, $mystring);
var_dump($array);我的输出是
array
0 => string 'traceroute <192.168.1.1>' (length=24)
1 => string '[ttl <120>]' (length=11)
2 => string '[wait <1500>]' (length=13)
3 => string '[no-dns]' (length=8)
4 => string '[source <192.168.1.11>]' (length=23)
5 => string '[tos <service>]' (length=15)
6 => string '{router <instance>]' (length=19)
7 => string '|' (length=1)
8 => string 'all}' (length=4)发布于 2012-01-27 19:02:35
是的,preg_split是有意义的,而且可能是最有效的方法。
尝试:
preg_split('/[\{\[<](.*?)[>\]\}]/', $mystring);或者,如果您想要匹配而不是拆分,您可能想要尝试:
$matches=array();
preg_match('/[\{\[<](.*?)[>\]\}]/',$mystring,$matches);
print_r($matches);已更新
我错过了您尝试获取令牌,而不是令牌的内容。我认为您将需要使用preg_match。尝试像这样的东西,作为一个好的开始:
$matches = array();
preg_match_all('/(\{.*?[\}])|(\[.*?\])|(<.*?>)/', $mystring,$matches);
var_dump($matches);我得到了:
Array
(
[0] => Array
(
[0] => <ip-address|dns-name>
[1] => [ttl <ttl>]
[2] => [wait <milli-seconds>]
[3] => [no-dns]
[4] => [source <ip-address>]
[5] => [tos <type-of-service>]
[6] => {router <router-instance>] | all}
)https://stackoverflow.com/questions/9032278
复制相似问题