简体   繁体   中英

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. If you can get the last $ to be served as a ? , it might be an idea to use parse_url() to parse it.

$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.

$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. On the other hand, this may be more flexible depending on how different the string can be.

Demo: http://codepad.org/vy5b9yX7

Docs: http://php.net/strtok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM