[英]How to extract parts using regular expression in PHP?
For example you have the following string: 例如,您具有以下字符串:
$text = "word1:text1@atpart/foo/do/myfood$textfinal";
The function will work like: 该功能将像:
$parts = array();
extract( $regular_exp, $text, $parts );
In the parts array we will get this: 在部件数组中,我们将获得以下信息:
$parts[0] = "word1";
$parts[1] = "text1";
$parts[2] = "atpart";
$parts[3] = "/foo/do/myfood";
$parts[4] = "textfinal";
Thanks! 谢谢!
This may not be what you are after, but the format you show looks almost like a URL with a username:password@domain
authentication in front. 这可能不是您想要的,但是显示的格式几乎类似于前面带有username:password@domain
身份验证的URL。 If you can get the last $
to be served as a ?
是否可以将最后的$
用作?
, it might be an idea to use parse_url()
to parse it. ,则可以使用parse_url()
进行解析。
$string = "word1:text1@atpart/foo/do/myfood?textfinal"; // notice the ?
$string = "none://".$string; // We need to add a protocol for this to work
print_r (parse_url($string));
Result: 结果:
Array (
[scheme] => none
[host] => atpart
[user] => word1
[pass] => text1
[path] => /foo/do/myfood
[query] => textfinal )
the advantage of this would be that it's pretty flexible if one or more parts can be missing in the incoming data. 这样做的好处是,如果传入数据中可能缺少一个或多个部分,则它非常灵活。 If that's not an issue, a regex may be more convenient. 如果这不是问题,则使用正则表达式可能会更方便。
尝试
$parts = preg_split('/[:@\$]+/', $text);
Without more details, this matches the proposed example: 没有更多细节,这与建议的示例匹配:
preg_match('#(.*?):(.*?)@(.*?)(/.*?)\$(.*)#', $text, $parts);
note that you will get the parts starting at index 1 instead of 0. 请注意,您将从零开始而不是从索引1开始获得零件。
$delims=':@$';
$word = strtok('word1:text1@atpart/foo/do/myfood$textfinal',$delims);
while ( $word!==false ) {
foreach( explode('/',$word,2) as $tmp){
$words[]=$tmp;
}
$word = strtok($delims);
}
var_dump($words);
On one hand this is probably overkill. 一方面,这可能是矫kill过正。 On the other hand, this may be more flexible depending on how different the string can be. 另一方面,根据字符串的不同程度,这可能更灵活。
Demo: http://codepad.org/vy5b9yX7 演示: http : //codepad.org/vy5b9yX7
Docs: http://php.net/strtok 文件: http : //php.net/strtok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.