Php提取字符之间的文本

时间:2013-05-30 07:32:37

标签: php regex extract preg-match-all preg-split

我从字符串中的来源获得响应

page <a href="${CLICK_URL}" target="_top">site not active</a> 

我需要将这些数据提取到数组中:

Array
(
    [0] => page
    [1] => ${CLICK_URL}
    [2] => _top
    [3] => >site not active  
)

我有线索使用preg_split()函数。请帮忙......

1 个答案:

答案 0 :(得分:3)

这对你有用吗?

<?php

$str = 'page <a href="${CLICK_URL}" target="_top">site not active</a>';

$regex = '
&
    ^                   # start of string
    (.*)                # string before link
    \s*                 # whitespace
    <a                  # start of <a> tag
    \s*                 # whitespace
    href="([^"]*)"      # match contents of href attribute
    \s*                 # whitespace
    target="([^"]*)"    # match contents of target attribute
    >                   # closing bracket of opening <a> tag
    ([^<]*)             # match html between opening and closing <a> tag
    </a>                # closing </a> tag
    $                   # end of string
&x';

// the 'x' modifier enables the possibilty to add comments in a regex
// http://php.net/manual/en/reference.pcre.pattern.modifiers.php

preg_match(
    $regex,
    $str,
    $matches
);

print_r($matches);

输出:

Array
(
    [0] => page <a href="${CLICK_URL}" target="_top">site not active</a>
    [1] => page
    [2] => ${CLICK_URL}
    [3] => _top
    [4] => site not active
)