简体   繁体   English

PHP正则表达式preg_match_all用于字符串

[英]PHP regex preg_match_all for string

I have the following string: 我有以下字符串:

keyword|title|http://example.com/ 关键字|标题| HTTP://example.com/

I would like to use the PHP function 我想使用PHP函数

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

currently 目前

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

and I get $matches array: 我得到$ matches数组:

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? 我如何修改$ anchor才能实现此目的?

The easiest way would be to use explode() instead of regular expressions: 最简单的方法是使用explode()而不是正则表达式:

$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: 如果您想继续使用正则表达式来避免手动循环,那么建议您在使用的[\\w\\W]*语法上使用此正则表达式,以提高可读性:

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

It's a bit more robust with explicit negated character classes. 显式否定字符类的功能更强大。 (I assume neither title nor url can contain | here.) (我假设标题和url都不能包含| 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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