简体   繁体   中英

PHP regex preg_match_all for string

I have the following string:

keyword|title|http://example.com/

I would like to use the PHP function

preg_match_all ( $anchor, $key, $matches, PREG_SET_ORDER) )

currently

$anchor='/([\w\W]*?)\|([\w\W]*)/';

and I get $matches array:

Array
(
    [0] => Array
        (
            [0] => keyword|title|http://example.com/
            [1] => keyword
            [2] => title|http://example.com/
        )

)

I would like to get

matches[1]=keyword
matches[2]=title
matches[3]=http://example.com

How would I have to modify $anchor to achieve this?

The easiest way would be to use explode() instead of regular expressions:

$parts = explode('|', $str);

Assuming none of the parts can contain | . But if they could, regex wouldn't help you much either.

If you want to keep using the regex to avoid a manual loop, then I'd recommend this over the used [\\w\\W]* syntax and for readability:

$anchor = '/([^|]*) \| ([^|]*) \| ([^\s|]+)/x';

It's a bit more robust with explicit negated character classes. (I assume neither title nor url can contain | here.)

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